Click to See Complete Forum and Search --> : Float values have too many digits


learninghtml
10-11-2003, 09:28 PM
Hi,
I have a function which converts a string from a menu list of values (1,2,3...,10) to an integer and then multplies it by 3.20. The result is displayed in a text box.

Multiplying by three or six gives the correct answer but with extra 0's added.

For most other numbers it works fine.

I have tried limiting the size of the "result" text box to five characters and using the num.toFixed(2) and the num.toPrecision(5) methods but they don't seem to work.


This function calculates the cost of children's play tickets required. The javascript function is as follows....

function calctotalchildcost(numtickets) {
var costresult = parseFloat(parseInt(numtickets,10) * 3.20)
var costtest = costresult % 1
if(costtest != 0) { // Is result an integer?
costresult += "0" } // No, add "0" to result
else {
costresult += ".00" // Yes, add ".00" to result
}
return costresult
}

costtest is used to determine if I need to add one or two zeros on the end of the value....

E.G.

1 * 3.20 gives 3.2 but for currency need to add a trailing zero.

This gives 3.20

AND..

10 * 3.20 gives 32 but for currency need to add a decimal point and two trailing zeros.

This gives 32.00

That bit works fine. The problem seems to be with the parseFloat() function.

Can anyone help me with this?

Many thanks in advance.

Charles
10-12-2003, 06:12 AM
Computers are very bad calculators and numbers are just approximate.

<input type="text" onchange="this.value = Number(this.value * 3.2).toFixed(2)">

learninghtml
10-12-2003, 09:32 AM
Hi Charles,
It works a treat. I was using the method in the wrong place. I've ditched the function and done it in the way you suggested.


Many thanks