Question

I'm giving it a price as 19.90 and it ouputs 19.98, the original calculation is:

 $('#price').text((Math.floor(price * 100) / 100) + ' Euro');

Here's a JsFiddle just with the Math.floor part which is the one giving problems:

http://jsfiddle.net/dLNnp/

I'm expecting it to give 19.9 again!

Was it helpful?

Solution

In your particular case, you should maybe switch to Math.round() to cope with the inaccuracies when using floating point arithmetic.

$('#price').text((Math.round(price * 100) / 100) + ' Euro');

When you look at the internal presentation, you will see something like this:

19.90 * 100
> 1989.9999999999998

JavaScript floating point numbers are not able to represent your number exactly, but use something close to your real number. When you now use Math.floor() on this value, you get 19.89 instead of 19.90.

To get a general idea about the subject, I refer you to this question:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top