math - Avoiding problems with JavaScript's weird decimal calculations -


i just read on mdn 1 of quirks of js's handling of numbers due being "double-precision 64-bit format ieee 754 values" when .2 + .1 0.30000000000000004 (that's article reads, 0.29999999999999993 in firefox). therefore:

(.2 + .1) * 10 == 3 

evaluates false.

this seems problematic. can done avoid bugs due imprecise decimal calculations in js?

i've noticed if 1.2 + 1.1 right answer. should avoid kind of math involves values less 1? because seems impractical. there other dangers doing math in js?

edit:
understand many decimal fractions can't stored binary, way other languages i've encountered appear deal error (like js handles numbers greater 1) seems more intuitive, i'm not used this, why want see how other programmers deal these calculations.

in situations these tipically rather make use of epsilon estimation.

something (pseudo code)

if (abs(((.2 + .1) * 10) - 3) > epsilon) 

where epsilon 0.00000001, or whatever precision require.

have quick read @ comparing floating point numbers


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -