Created
November 18, 2016 22:15
-
-
Save CraigRodrigues/e79bf0c98cb3d17e4c1dd5a5e4806bcf to your computer and use it in GitHub Desktop.
Converting cm to inches to nearest 1/16th inch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The company I work for creates custom acrylic cases based on customer's inputted dimensions. | |
// For fabrication our dimensions go down to the nearest 1/16th inch. | |
// International customers may use cm (or mm) and this is a program that will attempt to convert cm to inches | |
// down to the nearest 16th of an inch and display the result as a reduced fraction. | |
// 1 cm is equivalent to 0.39370 inches. | |
// EXAMPLE: 16.4 cm = 6 7/16 inches | |
// EXAMPLE: 10.5 cm = 4 2/16 or 4 1/8 inches | |
const CM_TO_INCHES = 0.39370; | |
// convert centimeter to inches (5 decimal places) | |
var centimetersToInches = function(centimeters) { | |
var inches = centimeters * CM_TO_INCHES; | |
return inches.toFixed(5); | |
}; | |
// split converted inches into everything before the decimal and everything after the decimal | |
var before = function(n) { | |
return Math.floor(n); | |
}; | |
var after = function(n) { | |
var fraction = n.toString().split('.')[1]; | |
return parseInt(fraction, 10); | |
}; | |
// convert the "after" to the nearest 1/16th inch | |
var nearest16th = function(n) { | |
var denominator = 16; | |
var numerator = Math.round(16 * (n * 0.00001)); | |
// reduce the fraction | |
while (numerator % 2 === 0) { | |
numerator /= 2; | |
denominator /= 2; | |
} | |
return numerator + "/" + denominator; | |
} | |
console.log(before(centimetersToInches(10.3)) + " " | |
+ nearest16th(after(centimetersToInches(10.3))) + " inches"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nearest16th has an infinite loop bug, try:
nearest16th(after(centimetersToInches(60)))
Need to add protection to when numerator is 0: