PDA

View Full Version : repetitive adding of big number in javascript


sakthivel
02-14-2003, 02:56 PM
Hi there,

appreciate some help here.

I have an array of size 200.
And all of them have the value of 99999999.99

How do I add all 200 elements of the array?

Whe i do it in a for loop, i get a wrong answer. I get an answer
with more than two decimal places!

Thank you for ur time.

-Sakthi

jalarie
02-14-2003, 03:13 PM
There is no way for the computer, working base 2, to store an exact value for .99 base 10. It has to either truncate or round off after some number of bits. Usually, this is so far out that you don't see it in the result, but you've multiplied that error by 200, so it shows up.

If you are working with money, switch everything to pennies, do the math, and then switch back to dollars. The computer would then be working with integer values, and they get stored exactly.

beetle
02-14-2003, 05:11 PM
:Dvar nums = new Array();

for ( var i = 0; i < 200; i++ )
nums[i] = 9999999999;

var total = eval(nums.join("+")) / 100;