【问题标题】:Multiplication gives approximate results乘法给出近似结果
【发布时间】:2017-06-23 08:54:12
【问题描述】:

嗯,我在客户端遇到了舍入问题,然后在后端进行了验证,并且由于这个问题验证失败。这是上一个问题Javascript and C# rounding hell

所以我正在做的是:

在客户端:

I have 2 numbers: 50 and 2.3659
I multiply them: 50 * 2.3659  //118.29499999999999
Round to 2 decimal places: kendo.toString(50 * 2.3659, 'n2') //118.29

在后台(C#):

I am doing the same: 50 and 2.3659
I multiply them: 50 * 2.3659  //118.2950
Round to 2 decimal places: Math.Round(50 * 2.3659, 2) //118.30

验证失败。我可以在客户端做点什么吗?

【问题讨论】:

  • 你知道floating math "is broken",对吧?
  • 对,但问题是在这种情况下我能做什么?您是否建议我丢弃业务验证并提交不正确的结果?
  • 将它们作为整数相乘,而不是作为浮点数。 50 * 23659 - 然后移动你认为合适的小数点。然后你会在任何地方得到相同的结果。这并不理想,但它会起作用。
  • @Mistalis,不可能。
  • 那么你最好的选择可能是一个库,它定义了一个实际的十进制类型或允许你对作为字符串的数字进行数学运算。

标签: javascript


【解决方案1】:

你能试试下面的 parseFloat 和 toFixed 函数吗:

   var mulVal = parseFloat(50) * parseFloat(2.3659);
   var ans = mulVal.toFixed(2);
   console.log(ans);

【讨论】:

    【解决方案2】:

    Javascript 算术并不总是准确的,这样的错误答案并不罕见。对于这种情况,我建议您使用Math.Round()var.toFixed(1)

    使用 Math.Round:

    var value = parseFloat(50) * parseFloat(2.3659);
    var rounded = Math.round(value);
    console.log(rounded);
    

    118 打印到控制台。

    使用 toFixed() 方法:

    var value = parseFloat(50) * parseFloat(2.3659);
    var rounded = value.toFixed(1);
    console.log(rounded);
    

    118.3 打印到控制台。

    请注意,使用toFixed(2) 将给出118.29 的值。

    希望这会有所帮助!

    【讨论】:

    • 是的,我需要四舍五入到 2,你很幸运 toFixed(1) 给出了正确的结果......
    【解决方案3】:

    尚未对此进行广泛测试,但以下函数应模拟“MidPointToEven”舍入:

    function roundMidPointToEven(d, f){		
        f = Math.pow(10, f || 0);  // f = decimals, use 0 as default
        let val = d * f, r = Math.round(val); 
        if(r & 1 == 1 && Math.sign(r) * (Math.round(val * 10) % 10) === 5)
        	r +=  val > r ? 1 : -1;  //only if the rounded value is odd and the next rounded decimal would be 5: alter the outcome to the nearest even number
        return r / f;
    }
    
    for(let d of [50 * 2.3659, 2.155,2.145, -2.155, 2.144444, 2.1, 2.5])
        console.log(d, ' -> ', roundMidPointToEven(d, 2)); //test values correspond with outcome of rounding decimals in C#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 2019-03-24
      • 2015-06-17
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多