Skip to content

Instantly share code, notes, and snippets.

@kogcyc
Last active November 1, 2017 16:44
Show Gist options
  • Save kogcyc/2b6dd50a90ade8ec47ebf6f5e721f5c7 to your computer and use it in GitHub Desktop.
Save kogcyc/2b6dd50a90ade8ec47ebf6f5e721f5c7 to your computer and use it in GitHub Desktop.
convert millimeters to inches and fractional eigths of an inch
# if you want to return something other than 1/8ths an inch
# then change the two 8.0s and the 8 to that sometheing else
# or start using millimeters for goodness' sake
from math import ceil,modf
def mm2inch(millimeters):
a = float(millimeters) / 25.4 # mms -> inches
b = modf(a)[0] # 0 is the
c = b * 8.0
d = ceil(c) # using ceil() has the effect of rounding up to the nearest [1/8] - using round() would give better accuracy
if (d == 8):
g = str(int(modf(a)[1]+1.0))
return g
else:
e = (d/8.0).as_integer_ratio()
f = str(e[0]) + '/' + str(e[1])
g = str(int(modf(a)[1]))
h = g + ' ' + f
return h
#
# so here's how it works:
#
# take a length in millimeters like 137
#
# devide it by 25.4 to get inches:
#
# 5.39370
#
# take the fractional portion, 0.39370, and multiple it by [8]:
#
# 3.1496
#
# then round that [or in my case with ceil()] round it UP] to the nearest integer:
#
# 3 [4]
#
# take that and divide it by [8]:
#
# 0.375
#
# and then use as_integer_ratio() to make that into (3, 8), which means 3/8ths
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment