How to deal with floating point number precision in JavaScript? -


i have following dummy test script:

function test(){     var x = 0.1 * 0.2;     document.write(x); } test(); 

this print result 0.020000000000000004 while should print 0.02 (if use calculator). far understood due errors in floating point multiplication precision.

does have solution in such case correct result 0.02? know there functions tofixed or rounding possibility, i'd have whole number printed without cutting , rounding. wanted know whether 1 of has nice, elegant solution.

of course, otherwise i'll round 10 digits or so.

from floating-point guide:

what can avoid problem?

that depends on kind of calculations you’re doing.

  • if need results add exactly, when work money: use special decimal datatype.
  • if don’t want see decimal places: format result rounded fixed number of decimal places when displaying it.
  • if have no decimal datatype available, alternative work integers, e.g. money calculations entirely in cents. more work , has drawbacks.

note first point applies if need specific precise decimal behaviour. people don't need that, they're irritated programs don't work correctly numbers 1/10 without realizing wouldn't blink @ same error if occurred 1/3.

if first point applies you, use bigdecimal javascript, not elegant @ all, solves problem rather providing imperfect workaround.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -