Click to See Complete Forum and Search --> : Rouding to two positions behind the comma?


morty
01-15-2004, 11:05 AM
Sorry, i already asked a simular question about this topic yesterday, but i still couldn't figure it out.
I have a form that calculates prices, but sometimes i get more than tow positions behind the comma. I know how i can round, but i don't know how i can round to two positions behind the comma!?
If you choose a one in all three menus in the following code you will see my problem(the result is: 389.40000000000003).

<html>
<head>

<script language="JavaScript" type="text/JavaScript">
function price() {
var two = parseFloat(window.document.form1.menu1.value);
var three = parseFloat(window.document.form1.menu2.value);
var four = parseFloat(window.document.form1.menu3.value);
var five = two + three + four;
window.document.form1.textfield.value = five;
}
</script>
</head>

<body>
<form name="form1">
<select name="menu1" size="1" onChange="price()">
<option value="0">0</option>
<option value="129.80">1</option>
</select>
<br>
<select name="menu2" size="1" onChange="price()">
<option value="0">0</option>
<option value="129.80">1</option>
</select>
<br>
<select name="menu3" size="1" onChange="price()">
<option value="0">0</option>
<option value="129.80">1</option>
</select>
<input type="text" name="textfield">
</form>

<br>
</body>
</html>

Pittimann
01-15-2004, 11:17 AM
Hi!

If you alter your function like this, it should work:

function price() {
var two = parseFloat(window.document.form1.menu1.value);
var three = parseFloat(window.document.form1.menu2.value);
var four = parseFloat(window.document.form1.menu3.value);
var five = (two + three + four).toFixed(2);
window.document.form1.textfield.value = five;
}

Cheers - Pit

requestcode
01-15-2004, 11:31 AM
Does "toFixed()" actually round or just fix it to two decimal positions? I thought you would have to use the round() method of the Math object. for example:


var five=(Math.round((two + three + four) * Math.pow(10,2)))/100

Pittimann
01-15-2004, 11:35 AM
Hi!

It rounds:

http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/number.html#1207032

Cheers - Pit

morty
01-15-2004, 11:46 AM
Thanks (Danke:)) Pittimann, now it works!!

But i read, that toFixed need ie5.5 or higher to work. So the idea of requestcode might be usefull in some cases.

requestcode
01-15-2004, 01:50 PM
That is much easier than my example if you want to round to two numbers. Thanks.