Robin Heller
Robin Heller

Reputation: 420

Strange results while adding / subtracting Floats in Javascript

I'm experimenting with JavaScript for the first time. My objective is to build a little 'configurator'. On my page, there are 2 buttons triggering the following functions onclick:

function default()
{
 curPrice = parseFloat(document.getElementById('price').innerHTML);
 newPrice = curPrice-priceEngraving;
 document.getElementById('price').innerHTML=newPrice;
}

and the other one looks like this:

function engrave()
{
var str = document.getElementById('price').innerHTML;
newPrice = curPrice+priceEngraving;
document.getElementById('price').innerHTML=newPrice;
}

priceEngraving is defined as 1 and the "default" innerHtml of #price is 5.30. When pressing button 1, the following result comes up:
6.3

This is okay and the expected result (appending a 0 on the end isn't too hard).

When firing button #2 the following result comes up: 5.3000000000000004

I don't know where's the problem in my code. I also tried ++ and -- (which I don't prefer because, as you know, prices are subject to change).

Also, I know about the security concerns when using JavaScript, but this one's only optical.

Upvotes: 6

Views: 4233

Answers (2)

halex
halex

Reputation: 16403

The problem is that some numbers can not be representated precisely as a floating point number. If you always want 2 decimal places then you can use the method toFixed(2) (documentation) on your numbers.

document.getElementById('price').innerHTML=newPrice.toFixed(2);

Upvotes: 2

davehale23
davehale23

Reputation: 4372

You are having floating point problems. See this post for details, the issues have been covered there in detail. Basically there is no way to map what you have accurately enough.

Upvotes: 0

Related Questions