3

Possible Duplicate:
Elegant workaround for JavaScript floating point number problem

If I perform the following operation in Javascript:

0.06120*400

The result is 24.48.

However, if I do this:

24.48/400

The result is:

0.061200000000000004

JSFiddle: http://jsfiddle.net/zcDH7/

So it appears that Javascript rounds things differently when doing division and multiplication?

Using my calculator, the operation 24.48/400 results in the correct answer of 0.0612.

How should I deal with Javascript's inaccurate division? I can't simply round the number off, because I will be dealing with numbers of varying precision.

Thanks for your advice.

Community
  • 1
  • 1
Nate
  • 26,164
  • 34
  • 130
  • 214
  • 1
    Floating point arithmetic is _always_ inaccurate. Javascript's not to blame. – John Dvorak Nov 17 '12 at 17:00
  • 1
    Floating point operations are not meant to be _100%_ accurate. This applies to almost all programming languages, not just JavaScript. – Salman A Nov 17 '12 at 17:00

1 Answers1

4

You can get the correct result with simply using:

var a = 24.48/400;
console.log(a.toFixed(6));

And because typeof a.toFixed(6) === 'string' you can:

var a = 24.48/400;
console.log(parseFloat(a.toFixed(6)));
  • The argument of toFixed is the number of decimals you want.
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68