java tofixed,四舍五入到Java的toFixed()方法

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 .

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

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.

解决方案

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:

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 .

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值