Skip to content

Instantly share code, notes, and snippets.

@chayanforyou
Forked from redteam-snippets/decimalToFraction.js
Created September 28, 2022 04:00
Show Gist options
  • Save chayanforyou/093beda925597f69941b3e4a792c1857 to your computer and use it in GitHub Desktop.
Save chayanforyou/093beda925597f69941b3e4a792c1857 to your computer and use it in GitHub Desktop.
JavaScript: Decimal To Fraction
// Adapted from: http://bateru.com/news/2011/11/improved-code-for-javascript-decimal-to-fraction/
function gcd(a, b) {
return (b) ? gcd(b, a % b) : a;
}
var decimalToFraction = function (_decimal) {
var top = _decimal.toString().replace(/\d+[.]/, '');
var bottom = Math.pow(10, top.length);
if (_decimal > 1) {
top = +top + Math.floor(_decimal) * bottom;
}
var x = gcd(top, bottom);
return {
top : (top / x),
bottom : (bottom / x),
display : (top / x) + ':' + (bottom / x)
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment