View Full Version : round off error

09-13-2008, 05:06 AM
Math.log(1000) / Math.log(10) = 3, not 2.9999999999996

How do I make Javascript acknowledge this, even if I must lose the final digit?

I've tried this:

g = Math.log(a)/Math.log(b);
g = g * 10000000000000;
g = g + +0.0000000000005;
g = parseInt(g);
g = parseFloat(g / 10000000000000);

which is typical code for rounding. But it didn't work. I lost the final 6, but I still get a string of 9s.

09-13-2008, 06:25 AM

Philip M
09-13-2008, 07:55 AM

Math.round() rounds to the nearest integer - OK here.

If you want to round a decimal number to (say) two decimal places:-

x = 3.7646386370435;
x = x * 100; // take it up two places
x = Math.round(x); // do the round
x = x/100; // take it back down two places
alert (x);


x = 3.764638638670435;
x = x.toFixed(2) * 1; // toFixed() converts to a string so multiply by 1 to revert to number if further processing is required. Omit if x to display only.
alert (x);

At least once per year, some group of scientists will become very excited and announce that whatever they announced last year about global warming is wrong.

09-14-2008, 12:01 AM
Your first method works perfectly. Thanks!