Click to See Complete Forum and Search --> : Mathematically challenged


Taliv
03-28-2003, 12:42 AM
When cnt = 3, the following code returns
US$ 2.8499999999999996 instead of 2.85!!!!

Any suggestions how to solve this or round it up to 2.85????

amount = (cnt*0.95)
document.Listing.total.value = "US$ "+ amount

Thank You

gil davis
03-28-2003, 05:32 AM
The problem stems from how numbers are stored. Real numbers are stored as floating point numbers, and results are sometimes not precise.amount = (cnt * 95) / 100;There may still be cases where this gives strange results, but it definitely works right for 3.

Another approach:dollars = Math.floor(cnt * 0.95);
cents = cnt * 95 % 100;
amount = "U.S. $ " + dollars + "." + cents;This has the advantage of giving you two decimal places.