{{ message }}

Instantly share code, notes, and snippets.

# CraigRodrigues/convert.js

Created Nov 18, 2016
Converting cm to inches to nearest 1/16th inch
 // 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('.'); 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");

### omerts commented Sep 14, 2020 • edited

 nearest16th has an infinite loop bug, try: `nearest16th(after(centimetersToInches(60)))` Need to add protection to when numerator is 0: ```var nearest16th = function(n) { var denominator = 16; var numerator = Math.round(16 * (n * 0.00001)); // reduce the fraction while (numerator && numerator % 2 === 0) { numerator /= 2; denominator /= 2; } return numerator + "/" + denominator; }```