11

When I am adding two textbox values that are 1.001 and 0.001 and then I do a parseFloat I get 1.0019999999. I want it 1.002 . Can you help me?

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44

5 Answers5

27

The Javascript Number class has a toFixed() function that will get you what you want.

So you could do parseFloat("1.0019999").toFixed(3) and that would give you 1.002.

The parameter (3 in this case) is the number of digits to show after the decimal point

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
17 of 26
  • 27,121
  • 13
  • 66
  • 85
  • Thank you, 17 of 26. I didn't know about the toFixed() function. – pmg Oct 06 '08 at 12:32
  • The toFixed() method returns a string(instead of number) representation of a number in fixed-point notation. So we should be careful while dealing with toFixed() method. – pramodc84 Jan 25 '10 at 11:41
10

0.002 cannot be accurately represented as a base 2 number. Similar to the way that 1/3 can't be represented in base 10.

1/3 = 0.33333... recuring. To represent the number accurately in base 10, you would need an infinite number of decimal digits.

0.002 is a number that can be accurately represented in base 10 (as we see here), but not in base 2, as used by computers. To represent this number accurately, would take an infinite number of binary digits.

SpoonMeiser
  • 19,918
  • 8
  • 50
  • 68
6

The javascript methods Number.toFixed() and Number.toPrecision() can help here, but they return a String. A possible solution is as follows:

var x = parseFloat(parseFloat("1.0019999999").toPrecision(3));
Lorenzo Polidori
  • 10,332
  • 10
  • 51
  • 60
6

This is a known problem: see accuraty problem and the minimisation of the accuracy problem: minimisation

Burkhard
  • 14,596
  • 22
  • 87
  • 108
0

If you want to a quick fix you can round to the nearest thousandth

Math.round((1.001+0.001)*1000)/1000

user19745
  • 3,499
  • 8
  • 25
  • 21
  • I voted that one down, because JS now has helper methods for such tasks and readable code is important. – feeela Apr 25 '18 at 10:12