Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why doesn't it add up correctly? 1

Status
Not open for further replies.

Nottoobright

Technical User
Oct 10, 2001
17
0
0
GB
I have an expenses form which usually adds up correctly, however when I put in the following figures it adds up with this reacurring number. Why?

The figures are:
4.50
2.95
6.80
7.70
2.40

and it adds them up to be:
24.349999999999998

instead of 24.35

The code is this:

var sub = 0;

if (T1.value > 0){
sub=sub + eval(T1.value)};
if (T2.value > 0){
sub=sub + eval(T2.value)};
if (T3.value > 0){
sub=sub + eval(T3.value)};
if (T4.value > 0){
sub=sub + eval(T4.value)};
if (T5.value > 0){
sub=sub + eval(T5.value)};
if (T6.value > 0){
sub=sub + eval(T6.value)};
if (T7.value > 0){
sub=sub + eval(T7.value)};
if (T8.value > 0){
sub=sub + eval(T8.value)};
if (T9.value > 0){
sub=sub + eval(T9.value)};
if (T10.value > 0){
sub=sub + eval(T10.value)};
if (T11.value > 0){
sub=sub + eval(T11.value)};
total.value= sub;

Thanks
 
looks like this is the way math does it...
try something like:

var temp=24.349999999999998
temp=parseInt(temp*100)/100;
alert(temp) Victor
 
The REASON that it happens is because computers don't use decimal, they use binary, and just as there are some fractions that don't come out even in decimal (e.g. 1/3) there are some that don't come out even in binary, so they become repeating. Unfortunately there are a LOT of numbers that do that. It's not easy to represent 10ths and 100ths in terms of 1/2's, 1/4's, 1/8's, 1/16's, etc. (that's binary's fractional parts). Any time you work with numbers with fractional parts via javascript you're likely to run into this problem, especially if you do anything more complex than addition and subtraction. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
gooood post, Tracy :) even i understood it :) Victor
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top