将小数转换为分数/有理数

新手上路,请多包涵

在 JavaScript 中,有什么方法可以将十进制数(例如 0.0002 )转换为表示为字符串的分数(例如 “ 2/10000" )?

如果为此目的编写了名为 decimalToFraction 的函数,则 decimalToFraction(0.0002) 将返回字符串 "2/10000"

原文由 Anderson Green 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

您可以使用 Erik Garrison 的 fraction.js 库来执行此操作以及更多分数操作。

 var f = new Fraction(2, 10000);
console.log(f.numerator + '/' + f.denominator);


要做 .003 你可以做

var f = new Fraction(.003);
console.log(f.numerator + '/' + f.denominator);

原文由 Trent Earl 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用术语“小数到分数 js”进行一点谷歌搜索, 第一个产生了这个:

http://wildreason.com/wildreason-blog/2010/javascript-convert-a-decimal-into-a-simplified-fraction/

它似乎工作:

http://jsfiddle.net/VKfHH/

 function HCF(u, v) {
    var U = u, V = v
    while (true) {
        if (!(U%=V)) return V
        if (!(V%=U)) return U
    }
}
//convert a decimal into a fraction
function fraction(decimal){

    if(!decimal){
        decimal=this;
    }
    whole = String(decimal).split('.')[0];
    decimal = parseFloat("."+String(decimal).split('.')[1]);
    num = "1";
    for(z=0; z<String(decimal).length-2; z++){
        num += "0";
    }
    decimal = decimal*num;
    num = parseInt(num);
    for(z=2; z<decimal+1; z++){
        if(decimal%z==0 && num%z==0){
            decimal = decimal/z;
            num = num/z;
            z=2;
        }
    }
    //if format of fraction is xx/xxx
    if (decimal.toString().length == 2 &&
            num.toString().length == 3) {
                //reduce by removing trailing 0's
        decimal = Math.round(Math.round(decimal)/10);
        num = Math.round(Math.round(num)/10);
    }
    //if format of fraction is xx/xx
    else if (decimal.toString().length == 2 &&
            num.toString().length == 2) {
        decimal = Math.round(decimal/10);
        num = Math.round(num/10);
    }
    //get highest common factor to simplify
    var t = HCF(decimal, num);

    //return the fraction after simplifying it
    return ((whole==0)?"" : whole+" ")+decimal/t+"/"+num/t;
}

// Test it
alert(fraction(0.0002)); // "1/5000"

原文由 Alex Wayne 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题