四舍五入到Java的toFixed()方法 [英] Rounding in Javascript toFixed() method

查看:869
本文介绍了四舍五入到Java的toFixed()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道javascript中的 toFixed()方法将数字转换为字符串,并保留指定的小数位数,就像下面显示的代码一样,该代码设置了小数点后的位数小数点是 2

I have known that the toFixed() method in javascript converts a number into a string, keeping a specified number of decimals, just like the code shown below, which sets the number of digits after the decimal point to be 2 .

我的问题是:是否在必要时对数字进行四舍五入。如下面的代码所示,我将转换数字: 0.075 。我认为四舍五入0.075应该是0.08,因为 5 go up。但是,在下面的第一种情况下看起来很奇怪。所以我很困惑。

My question is: Whether the number is rounded when necessary. As in the code below, I would convert the number: 0.075. I think rounding 0.075 should be 0.08 as "5 go up". However, it looks weird in the first case below. So I was confused.

var a=0.25*0.3;
var res1 = a.toFixed(2);
console.log(res1);
//Output: a is 0.07 (Is there something wrong?)

var b=0.025*3;
var res2= b.toFixed(2);
console.log(res2);
//Output:b is 0.08

我知道问题可以通过使用Math.js解决。但是,我只是想知道问题的原因?是toFixed()方法的问题还是javascript中的数据类型的问题。

I have known the problem could be solved by using Math.js. However, I was just wondering the reason of the problem? Is a matter of toFixed() method or a matter of data types in javascript.

推荐答案

文档 toFixed() 在必要时进行取整。舍入行为将舍入在-.5< 5的范围内。 x< = +.5的数字。

As stated in the docs, toFixed() does round when necessary. The rounding behavior is to round in the range -.5 < x <= +.5 of the digit.

您观察到的奇怪行为与上面链接的文档中的注释一致:

The strange behavior you're observing is consistent with the note in the docs linked above:


浮点数不能精确地用二进制表示所有小数,这会导致意外结果,例如0.1 + 0.2 === 0.3返回false。

Floating point numbers cannot represent all decimals precisely in binary which can lead to unexpected results such as 0.1 + 0.2 === 0.3 returning false .

换句话说,这是浮点精度损失的经典情况-实际上,任何语言都将遇到这个问题。如果观察 a b 的完整输出,您会看到 a == 0.075 b == 0.07500000000000001 由于浮点精度-因此给定这些值与定义的舍入行为符合以<$ c取整$ c> a 到 .07 b 。 08

In other words, this is a classic case of floating point precision loss - a problem you'll encounter in virtually any language. If you observe the full outputs of a and b you'll see that a == 0.075 and b == 0.07500000000000001 due to floating point precision - and thus given these values it is consistent with the defined rounding behavior to round a to .07 and b to .08.

这篇关于四舍五入到Java的toFixed()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆