4

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.

pb2q
  • 58,613
  • 19
  • 146
  • 147
Robin Heller
  • 400
  • 5
  • 14

2 Answers2

1

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);
halex
  • 16,253
  • 5
  • 58
  • 67
0

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.

Community
  • 1
  • 1
davehale23
  • 4,374
  • 2
  • 27
  • 40
  • Thanks for the answer, it was more accurate, but the other answer has helped me more in finding an acceptable solution! – Robin Heller Oct 12 '12 at 19:19