【问题标题】:How to truncate extra zeros from floating point number如何从浮点数中截断多余的零
【发布时间】:2017-11-18 10:42:58
【问题描述】:

说: 变量 x = 6.450000000000003; 变量 y = 5.234500000000002;

这些是浮点除法的结果,所以需要去掉3和2。考虑到它们具有不同的精度水平,我如何将 x 修整为 6.45 和 y 修整为 5.2345?

【问题讨论】:

标签: javascript floating-point


【解决方案1】:

您可以使用Number#toFixed 并将字符串转换回数字。

var x = 6.450000000000003,
    y = 5.234500000000002;
    
x = +x.toFixed(5);
y = +y.toFixed(5);

console.log(x);
console.log(y);

【讨论】:

    【解决方案2】:

    您可以使用Math.round,但您必须选择精度。

    (否则,您将失去精确度,而您不希望这样!)

    var x = 6.450000000000003;
    var y = 5.234500000000002;
    
    
    console.log(Math.round(x * 1000000) / 1000000);
    console.log(Math.round(y * 1000000) / 1000000);

    【讨论】:

      【解决方案3】:

      试试这个功能。如果如您所说,您只是想删除结束数字并删除尾随零,那么以下代码可能会有所帮助。

          function stripZeroes(x){
              // remove the last digit, that you know isn't relevant to what 
              // you are working on
              x = x.toString().substring(0,x.toString().length-1); 
              // parse the (now) String back to a float. This has the added 
              // effect of removing trailing zeroes.
              return parseFloat(x);}
      
          // set up vars for testing the above function
          var x = 6.450000000000003;
          var y = 5.234500000000002;
          
          // test function and show output
          console.log(stripZeroes(x));
          console.log(stripZeroes(y));

      【讨论】:

      • 代码块本身通常不是有用的答案,并且更有可能吸引反对票。请解释您展示的解决方案是做什么的,以及为什么/如何该代码回答了这个问题。
      • OP 确实在寻找一种解决浮点不精确性的方法。最后可能有多个“额外”数字,它可能是一串 9 而不是 0。此外,此函数会破坏 具有尾随零 + 结束数字的数字。
      • 根据 OP 的评论,他们希望删除最后一个数字和零。我明白你在说什么,但我并不是要提供通用解决方案,而是针对 OP 指出的特定问题和参数的特定解决方案:“2 如何处理浮点数精度的可能重复在 JavaScript 中?– JJJ 6 月 15 日 20:04 我的意思是我要删除最后一个数字和所有零。– Mardymar 6 月 15 日 20:05"
      猜你喜欢
      • 1970-01-01
      • 2013-12-31
      • 2011-04-29
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多