In JavaScript, is there any way to convert a decimal number (such as 0.0002) to a fraction represented as a string (such as \"2/10000\")?
I
I know this is an old question, but I have created a function that has been greatly simplified.
Math.fraction=function(x){
return x?+x?x.toString().includes(".")?x.toString().replace(".","")/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length))+"/"+("1"+"0".repeat(x.toString().split(".")[1].length))/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length)):x+"/1":NaN:void 0;
}
Call it with Math.fraction(2.56)
It will:
string (use Math.fraction(2.56).split("/") for an array containing the numerator and denominator)Please note that this uses the deprecated arguments.callee, and thus may be incompatible in some browsers.
Test it here