Halaman

Rabu, 22 Desember 2010

[shared] floating point error in js

console.log(0.1+0.2); //-> 0.30000000000000004
console.log(0.1*0.2); //-> 0.020000000000000004

solution:
1. use x.toFixed(n) if you only need 5 or less decimal digit
2. use function from http://www.codingforums.com/showpost.php?p=483962&postcount=9
3. best solution, use js BigDecimal library https://github.com/jhs/bigdecimal.js or http://stz-ida.de/index.php?option=com_content&view=article&id=18&Itemid=32

summary:
use number 1 if decimal precision isn't really important (most likely), or use number 3 with some performance cost

Tidak ada komentar:

Posting Komentar