0

Today, I have seen strange issue with parseFloat in Javascript. When I an doing addition operation of the value I have seen some strange values, below are the examples:

parseFloat("31.099")+1;

Output:

32.099000000000004

Why do I have only problem with 31.099?

Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34
ChiranjeeviIT
  • 529
  • 1
  • 4
  • 17

3 Answers3

0

Floating numbers are always strange. Check out some descriptions in PHP Manual as well. There is a warning about precision.

Bimal Poudel
  • 1,214
  • 2
  • 18
  • 41
0

Most of the programming languages do this, when you add an int to a floating number, it will make an approximation of the result. One work around would be to create your floating type and separate the floating value from the integer value.

Manegan
  • 26
  • 5
0

Yes, floating point numbers are not always precise. It's because fractions cannot be precisely represented in binary.

To fix it, use toFixed() to round floating point numbers to the amount of precision you want. For example, for two decimal places:

num.toFixed(2)
kieranpotts
  • 1,510
  • 11
  • 8
  • Hi Kieran, thank you for your reply. But i am not sure fixed size of precision , In that how should i approach with toFixed(2) – ChiranjeeviIT Jul 09 '15 at 08:41