【问题标题】:toFixed function not working properly ( please give a reason not an alternative)toFixed 功能无法正常工作(请给出原因而不是替代方法)
【发布时间】:2020-08-22 00:53:04
【问题描述】:

toFixed() 函数对浮点值的响应不同。 例如:

 var a = 2.555;
 var b = 5.555;

console.log(a.toFixed(2));  /* output is 2.56 */ 
console.log(b.toFixed(2));  /* output is 5.55 */

对于 2.555/3.555,结果为 (2.56/3.56)

对于其他值(不确定所有值)它显示 #.55(# 指任何数字)

我很困惑,谁能帮帮我。

提前致谢。

【问题讨论】:

标签: javascript math


【解决方案1】:

Javascript 使用二进制浮点表示数字 (IEEE754)。 使用这种表示形式,唯一可以精确表示的数字是 n/2m 形式,其中 nm 都是整数。

分母是 2 的整数幂的任何非有理数都无法精确表示,因为在二进制中它是周期数(在点之后有无限的二进制数字)。

数字0.5(即1/2)很好,(二进制只是0.1₂)但例如0.55(即11/20)不能精确表示(二进制是0.100011001100110011₂…,即0.10(0011)₂ 最后一部分 0011₂ 重复无限次)。

如果您需要执行任何计算,其中结果取决于精确的十进制数字,您需要使用精确的十进制表示。如果小数位数是固定的(例如 3),一个简单的解决方案是将所有值乘以 1000...

2.555 --> 2555
5.555 --> 5555
3.7   --> 3700

并在进行乘法和除法时相应地调整您的计算(例如,在将两个数字相乘后,您需要将结果除以 1000)。

IEEE754 双精度格式对于最大为 9,007,199,254,740,992 的整数是准确的,这对于价格/值来说通常足够了(四舍五入通常是个问题)。

【讨论】:

    【解决方案2】:

    试试这个Demo Here

    function roundToTwo(num) {    
        alert(+(Math.round(num + "e+2")  + "e-2"));
    }
    
    roundToTwo(2.555);
    roundToTwo(5.555);
    

    【讨论】:

    【解决方案3】:

    toFixed() 方法取决于浏览器向下舍入或保留。

    这是这个问题的解决方案,检查最后的“5”

     var num = 5.555;
     var temp = num.toString();
    if(temp .charAt(temp .length-1)==="5"){
    temp = temp .slice(0,temp .length-1) + '6';
    }
    num = Number(temp);
    Final = num.toFixed(2);
    

    或者可重用的函数就像

    function toFixedCustom(num,upto){
    
         var temp = num.toString();
        if(temp .charAt(temp .length-1)==="5"){
        temp = temp .slice(0,temp .length-1) + '6';
        }
        num = Number(temp);
        Final = num.toFixed(upto);
        return Final;
    }
    
    var a = 2.555;
     var b = 5.555;
    
    console.log(toFixedCustom(a,2));  
    console.log(toFixedCustom(b,2));  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      相关资源
      最近更新 更多