Convert a decimal number to a fraction / rational number

前端 未结 11 1837
情歌与酒
情歌与酒 2020-12-01 16:36

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

11条回答
  •  被撕碎了的回忆
    2020-12-01 16:58

    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:

    • return NaN if the input is not a number
    • return undefined if the input is undefined
    • reduce the fraction
    • return a 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

提交回复
热议问题