Created
September 1, 2014 05:41
-
-
Save efreed/e53efa46535226d93748 to your computer and use it in GitHub Desktop.
Javascript decimal-to-fraction
This file contains hidden or 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
/* | |
* Will convert a float to an html fraction, guessing denominators up to 16. Handles errors from rounding to 2 decimals. | |
*/ | |
function AsFraction(num) { | |
if (num == "" || isNaN(num)) // sanity check | |
return num; | |
var int = Math.floor(num) | |
, decimal = num - int; | |
if (decimal < 0.005) // whole number, don't show fraction | |
return int; | |
if (int == 0) // we know there's a fraction by now, zero ints aren't interesting | |
int = ""; | |
for (var n = 2; n <= 16; n++) { | |
// If we take away as many 1/n as possible, is it within tolerance (0 +/- 0.03/n) ? | |
if ((decimal + (0.03 / n)) % (1 / n) < 0.06 / n) { | |
return int + " <sup>" + Math.round(decimal * n) + "</sup>/<sub>" + n + "</sub>"; | |
} | |
} | |
// can't help, return given value to two decimal places | |
return Math.round(num * 100) / 100; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment