PDA

View Full Version : Math.round Problem...please help!


Jonny5uk
01-29-2003, 12:47 PM
Hi there,

I'm having some real trouble with what seems to be a simple issue. I have spent hours looking at tutorials, but am a bit of a newbie with javascript and could really do with some help.

Here's the problem...

I am building a weather convertor, which simply changes mm into inches and vice versa for a rainfall conversion.

This works fine, but i can seem to round the results. I was wondering if this due and an error in my code or whether I need to declare any particular variables in the beginning.

Here's a snippet from the button in the code which generates the answer, where it won't work...

<input name=mm
onChange= "Math.round(4.56789)) inches.value = this.value/25.4" size=8>
</font> </div></td>
<td><div align="center"> </div></td>
<td><div align="center"><font size="2" face="Arial, Helvetica">
<input name=inches
onChange="mm.value = this.value * 25.4" size=8>
</font> </div></td>
<td><div align="center"> </div></td>
<td>&nbsp;</td>
<td><font size="2" face="Arial, Helvetica">
<input name="button322" type=button onClick=(this.value) value=Convert>
<input name="Clear2" type="reset" id="Clear2" value="Clear">


The above code is for 2 entry fields and two buttons. In one (top) I have tried to enter math.round code, the other I have not.

I haven't declared any math.round variables in the header, as not sure how to/or if I have to.

As you can see, I'm pretty lost and any help would be much appreciated !!

Thanks in advance

Jon

beetle
01-29-2003, 03:41 PM
Round to how many decimal places? 0? 2? 4?

Jonny5uk
01-29-2003, 04:29 PM
sorry, forgot to mention that in my hurry, 2 places would be ideal !

Thanks !

beetle
01-29-2003, 05:13 PM
Ok, what you really need here is a function.<html>
<head>
<title>!!!TEST!!!</title>
<script type="text/javascript">

function convert( value, field, type )
{
if ( value == "" )
{
alert( "You need to enter a value to convert!" );
return;
}
var conversion = 25.4;

if ( type == 1 ) // mm to inches
{
field.value = Math.round( parseFloat( value ) / conversion * 100 ) / 100;
}
else // inches to mm
{
field.value = Math.round( parseFloat( value ) * conversion * 100 ) / 100;
}
}

</script>
</head>
<body onload="doIt()">

<form name="myForm">

mm<input name="mm" size="8">
<input type="button" value="Convert to inches »" onclick="convert( this.form.mm.value, this.form.inches, 1 )">
<br />
in <input name="inches" size="8">
<input type="button" value="convert to mm »" onclick="convert( this.form.inches.value, this.form.mm, 0 )">
<br />
<input type="reset" id="Clear" value="Clear">


</form>


</body>
</html>

Jonny5uk
01-30-2003, 07:04 PM
Hi Beetle,

Just wanted to say a big thanks to for the help. I have got it sorted now, which has seriously got me out of a hole, so much appreciated.

I managed to modify the code by implementing the commands in your code.

Massively appreciated !

Thanks again

Jon