0

If I do the following:

parseInt(parseFloat(9.20)*100*1)/100 // returns 9.19

It returns 9.19 when I want it to return 9.20 what do I need to change to get it to return the correct value?

I have the same issue when I change it to:

parseInt(parseFloat(9.12)*100*1)/100 // returns 9.11

But any other value works fine:

parseInt(parseFloat(9.30)*100*1)/100 // returns 9.30 (correct)

UPDATE:

The solution was this:

(Math.round(9.20*100*1)/100).toFixed(2)
fidler2326
  • 101
  • 1
  • 4

2 Answers2

1

The problem is that 9.20*100 in Javascript returns 919.9999999999999, and not 920, because of floating point errors. When you do a parseInt() on that, it doesn't round to the nearest int, and instead truncates it to 919, which is why your final answer is wrong.

Instead of using parseInt(), a better method to use is Math.round(). This method rounds to the nearest int, turning your 919.99999 into 920, giving you the correct answer.

  • This seems to have done it. I've changed it to `(Math.round(parseFloat(9.20)*100*1)/100).toFixed(2)// returns "9.20"` Thanks! – fidler2326 Jun 16 '17 at 17:42
  • I just want to add that you don't need the parseFloat() in your code at all, parseFloat is used to turn a string, like `"9.2"` into the float `9.2`. Since your number seems to be a float already, and not a string, you should be able to remove the `parseFloat()` entirely. I'm also a little curious why you seem to be multiplying by 1? – Aryaman Tummalapalli Jun 16 '17 at 18:23
0

Because JavaScript uses binary arithmetic, floating point math is an approximation of the base 10 result.

One way to avoid this is to perform integral math, but multiplying your decimals up by a factor large enough to transform them to integers and then divide the answer back down by the same factor.

In this case, I'm not sure why you are using parseInt() or parseFloat() since you are not working with strings in the first place.

Lastly, when you do use parseInt() it is advisable to use the second (optional) argument and supply the radix (the base numeral system to be used to perform the operation) as you can get incorrect values back when the string to be parsed begins with "0" or "0x".

var result = parseInt(9.2*10, 10)/10 // returns 9.19

console.log(result);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71