View Full Version : Javascript Calculator Math Problem

Jan 29th, 2014, 12:16 AM
I'm using a javascript math calculator but the answer is not coming out like I need. When I multiply 3.50 x 3, I get an answer of 10.5 and I would like it to read 10.50. When I multiply 3x3, I get 9 and I would like it to read 9.00. I would be extremely grateful for help. Here is my script.

<script type="text/javascript">
function Calc(){
document.form1.fare2.value = d;

Jan 29th, 2014, 12:53 AM
function Calc(){
var VField1 = Number(document.form1.ArrivalPartyOver12.value);
var VField2 = Number(document.form1.ref.value);
var d = VField1*VField2;
document.form1.fare2.value = d.toFixed(2) || "";
You don't need eval. Use Number() instead. Although multiplying numeric strings produces the correct product, it is good practice to still convert them to a number data type.

Jan 29th, 2014, 04:57 PM
Thanks Glen. You're the man. Works perfectly. I'll look into what is meant by "number data type".

Jan 29th, 2014, 08:53 PM
alert(typeof "2"); //string
alert(typeof 2); //number

Jan 31st, 2014, 04:16 AM
[a number or variable storing one].toFixed(2) returns a string with the number rounded to 2 decimal places.