General discussion

Locked

Javascript multiplication question

By jacmari ·
Can someone tell me why this number does not come out? If I multiply it by 1000, the answer is correct.

Please help.

-- Jackie

var first_num = 1.15;
var second_num = 100;
var result = first_num * second_num;

document.writeln(first_num);
document.writeln(" * ");
document.writeln(second_num);
document.writeln(" = ");
document.writeln(result);

This conversation is currently closed to new comments.

2 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

floating point arithmetic

by Jay Eckles In reply to Javascript multiplication ...

The short answer is that the answer doesn't come out to what you expect because you're using floating point arithmetic. The FP representation of some numbers is only an approximation (although as you can see from the result of your script, a fairlyprecise approximation).

If you want the gory details about FPA, find any good computer architecture book or just google "Floating Point" or "Floating Point Arithmetic".

Jay

Collapse -

Possible Work Arounds

by Ed Woychowsky In reply to Javascript multiplication ...

Jay is right; the goofy results are due to a floating-point error. There is, however, a work around. Try braking the equation down into smaller pieces. For example, try the following:

var first_num = 1.15;
var second_num = Math.sqrt(100);
var result = (first_num * second_num) * second_num;

document.writeln(first_num);
document.writeln(" * ");
document.writeln(second_num * second_num);
document.writeln(" = ");
document.writeln(result);

You?ll find that the result is:
1.15 * 100 = 115

It won?t work for all numbers, but it will reduce the errors. Another possibility is to write your own functions to do fixed point arithmetic. It?s a technique that worked for IBM mainframes.

Back to Web Development Forum
2 total posts (Page 1 of 1)  

Related Discussions

Related Forums