View Full Version : Problem Using toFixed

07-31-2011, 08:06 PM
My code converts a running pace to speed in mph. Works fine but posts too many digits after the decmal point in my form. Tried several things but I'm new to javascript and could use some help. Thanks! Oh, my browser is IE8, but the problem is more likely me than it...



<!--This does not work... form.mph.value.toFixed(4) = 60 / (pmin + psec / 60);
Nor this... var mph; mph=mph.toFixed(4);

<script language="javascript">
function Speed(MIN, SEC, form)
var pmin = parseFloat(MIN);
var psec = parseFloat(SEC);
form.mph.value = 60 / (pmin + psec / 60);

function ClearForm(form)
form.input_pmin.value = "";
form.input_psec.value = "";
form.mph.value = "";


<form name="pace-speed" method="post">

<table style="font-size:14px; font-weight:bold;">

<td><input type="text" name="input_pmin" size="1">:</td>
<td><input type="text" name="input_psec" size="1"></td>

<td width="20"></td>

<td><input TYPE="button" VALUE="Speed" onClick="Speed(this.form.input_pmin.value, this.form.input_psec.value, this.form)"></td>

<td width="1"></td>

<td><input type="text" name="mph" size="8"></td>

<td width="2"></td>

<td><input TYPE="reset" VALUE="Clear" onClick="clearForm(this.form)"></td>




07-31-2011, 08:40 PM
did you try
form.mph.value = (60 / (pmin + psec / 60)).toFixed(4); ?

07-31-2011, 08:41 PM
toFixed() method convert a number to string, so you can't use it before completing all your calculations, and -of course- toFixed() works only on numbers (primitive or objects).

07-31-2011, 09:42 PM
did you try
form.mph.value = (60 / (pmin + psec / 60)).toFixed(4); ?

No, but that worked. Thanks!

I remember trying... form.mph.value.toFixed(4) = etc and it did not work

I just started trying this javascript stuff so I sure have a bunch to learn!

07-31-2011, 09:55 PM
no problem - I know how you feel. I'm about 1% into it :eek:

my take on why your solution didn't work is that the left side of the equals sign is for the new variable you are assigning a value to. the right side is used for modifications to pre-existing variables.

I'm sure somebody has a much better explanation than this.

the other bit was that - if you remember 8th grade math... BOMDAS - calculations within brackets get calculated first, which is why you needed to wrap the whole calculation in brackets, which calculates the number, then add the toFixed, which chops off the decimals.

that's the way I figure it, anyway. hope that helps.