42

JavaScript运算出现很多小数导致运算不精确的问题,用toFixed解决

 5 years ago
source link: http://ourjs.com/detail/5b829509ac52fe63eba50298?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

最近碰到一是微信充值的BUG,充值19.99变成充值19.98,导致金额前后,不 一致,仔细研究发现,JS某些小数运算会出现类似无限循环的小数

var fee = 19.99
var all = fee * 100
console.log(all)
> 1998.9999999999998

微信只认整数,应该传 1999,结果变成 1998.9999999999998 变成最后充值 19.98元 ,差了一分钱,导致金额不匹配。

其实这是JS在进行小数运算时,自动转换成了double所致,double的运算结果是不精确的,这种场景还有很多,比如:

console.log(0.1 + 0.2 == 0.3)
> false

console.log(0.1 + 0.2)
> 0.30000000000000004

console.log(2.4/0.8)
> 2.9999999999999996

解决方法:

1) 可以用toFixed来解决,如直接保留小数点后12位,可解决绝大部分场景的问题,注意toFixed后为字符串类型

console.log((0.1 + 0.2).toFixed(12) == 0.3)
> true

console.log((0.1 + 0.2).toFixed(12))
> 0.300000000000

console.log((2.4/0.8).toFixed(12))
> 3.000000000000

2) 先转成整型再运算

console.log((0.1 * 10 + 0.2 * 10) / 10)
> 0.3

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK