Skip to content

Instantly share code, notes, and snippets.

@efreed
Created September 1, 2014 05:41
Show Gist options
  • Save efreed/e53efa46535226d93748 to your computer and use it in GitHub Desktop.
Save efreed/e53efa46535226d93748 to your computer and use it in GitHub Desktop.
Javascript decimal-to-fraction
/*
* 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