Created
October 22, 2012 21:02
-
-
Save redteam-snippets/3934258 to your computer and use it in GitHub Desktop.
JavaScript: Decimal To Fraction
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
// 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) | |
}; | |
}; |
This is by far the most effective solution
It is wrong every time a whole number is inputted, so it should be:
function decimalToFraction(_decimal) {
if (_decimal%1 == 0){
return {
top : _decimal,
bottom : 1,
display : _decimal + ':' + 1
};
} else {
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
You should include case for 1, otherwise it incorrectly returns "1/10"