Click to See Complete Forum and Search --> : Script that calculates form fields coming up with very long numbers...


Madlantern
09-14-2003, 02:54 AM
I have written a script to add up some numbers entered into form fields on an order form page. When the "calculate" button is clicked and the math is applied, the numbers sometimes appear as they should and other times appear with a very long decimal number. I can't seem to track down the problem or any pattern. I figured that the problem is probably something easily explained by anyone with more than my limited experience. A copy of the page is at... http://www.madlantern.com/bkt/orderform.htm Can anyone tell me why these long numbers sometimes appear and how I can fix it?

Thanks a lot!

-M.Lantern

Fang
09-14-2003, 03:57 AM
All Javascript numbers are basically floating-point numbers, so any maths calculations can produce a decimal answer.
To avoid this use parseInt(aNumber) for intergers,
and/or Math.round(aNumber) , Math.floor(aNumber) or Math.ceil(aNumber) to round a number.
The Maths object (http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/math.html#1193138) and some theory with examples (http://www.merlyn.demon.co.uk/js-round.htm)

Charles
09-14-2003, 07:19 AM
<script type="text/javascript">
<!--
alert (Math.PI.toFixed(4))
// -->
</script>

Madlantern
09-14-2003, 04:33 PM
Thanks again,

Charles, I think the toFixed is the way I will go with the totals. That works wonderfly... but I'm still curious as to why the long numbers happen in the first place. Do you know? I've noticed that (the initial value of 19.95) when multiplied by quantities of 3, 6, 9, 12, 13, 15, 18, 23, 24 and on come up with that long decimal number. On first appearance, there seems to be a pattern, but it slowly changes as the numbers get higher.

Fang, I may try the parseInt in some way on the quantities to insure that quantities get into the calculation as integers. Thanks for your help and resources!

-M.Lantern

Charles
09-14-2003, 05:57 PM
Computers are actually bad with numbers. Each number is only allotted a certain ammount of space so they approximate the value.