メモ用サブブログ

子曰わく學びて時にこれを習う。

Javascript 小数点足し算

> 1+2 === 3
true
> 0.3 === 0.3
true
> 01+0.2 === 0.3
false
> 0.1+0.2
0.30000000000000004

Why does this happen? 0.1 +0.2 is equal to 0.30000000000000004. What you need to know is that all JavaScript numbers are floating points represented internally in 64 bit binary according to the IEEE 754 standard. For more explanation, take a look to this blog post.

You can use toFixed() and toPrecision() to resolve this problem.

45 Useful JavaScript Tips, Tricks and Best Practices | Flippin' Awesome