Discussion Locked

Javascript multiplication question

0 helpful
2 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

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);

2 replies

by jay eckles

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

by ed woychowsky

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.

This discussion is closed to new replies.