Click to See Complete Forum and Search --> : Adding two numbers with decimals
kevin86
06-26-2003, 01:09 PM
Hi, looking for some help here. All I am trying to do is add two numbers. 138.9 + 27.33 and instead of 166.23 i get 166.2300000000002. Can anyone tell me why? Here is my code
function button1_onclick() {
var TallyAmt = 0;
ThisAmt = document.form1.text1.value;
TallyAmt = (TallyAmt + (ThisAmt * 1));
alert (TallyAmt);
ThisAmt = document.form1.text2.value;
TallyAmt = (TallyAmt + (ThisAmt * 1));
alert (TallyAmt);
ThisAmt = document.form1.text3.value;
TallyAmt = (TallyAmt + (ThisAmt * 1));
alert (TallyAmt);
}
Thanks a bunch
Use toFixed() (http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/number.html#1200964) to return it to a certain number of decimal places.
David Harrison
06-26-2003, 03:08 PM
Computers are crap with decimals so I've found that this would be the best way to add two variables a and b:
var n=0;
var o=0;
while(Math.round(a*Math.pow(10,n))!=(a*Math.pow(10,n))){n++;}
while(Math.round(b*Math.pow(10,o))!=(b*Math.pow(10,o))){o++;}
var p=(n>=o)?n : o ; // Had to leave spaces here because : o turns into :o
a=a*Math.pow(10,p);
b=b*Math.pow(10,p);
answer=(a+b)/Math.pow(10,p);
It's a bit long winded but it's more accurate.
What's wrong with toFixed()?
David Harrison
06-27-2003, 06:12 AM
That will only work to return a specified amount of decimal places whereas mine will return the actual number of decimal numbers (up to about 20 anyway).
138.9 + 27.33 should only return two decimals.
David Harrison
06-27-2003, 12:54 PM
Yes, but if he used toFixed() and set it to return two decimal places, what if he wanted to add 23.8306 and 478.2669, they both have four decimal places.
Originally posted by lavalamp
Yes, but if he used toFixed() and set it to return two decimal places, what if he wanted to add 23.8306 and 478.2669, they both have four decimal places. Umm... He would set it to return four decimal places...
David Harrison
06-27-2003, 01:58 PM
What if he didn't know how many dp's the numbers were going to be to?