6

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.

1

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Thanks for the answer, it was more accurate, but the other answer has helped me more in finding an acceptable solution!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.