~ overflow ~

Javascript Floating Point Issues

by z3n on Apr.01, 2010, under Coding, Tips & Hints

Problem:

Javascript floating point issues.

Solution:

It’s well known that javascript has major issues when it comes to precision math, even the simplest operations tend to be a nightmare. Although i was aware of that i suddenly found myself into another tricky thing with zeros on the left (eg: 025).

To avoid issues with javascript rounding issues I get all numbers converted to strings, stripping their floating point, this only works if all numbers are from the same precision or if you do a function do that, since there’s no rounding function (besides .toFixed) that does that proprietly.

So, in sum, 1.23 will be calculated as 123, eg:

var a = 1.23;
var b = 4.56;
a = parseInt(a.toString().replace(/\./g,"")); // 1.23 -> 123
b = parseInt(b.toString().replace(/\./g,"")); // 4.56 -> 4.56
var x = a + b; // = 579
x=x.toString();
return x.substr(0,x.length-2)+"."+x.substr(x.length-2);

Now that’s good, right…?? Apparently yes, but let’s do another example:

var a= 0.25;
a = parseInt(a.toString().replace(/\./g,"")); // 0.25 -> 025
var x = 1*a; // 1* 025 = 025  -- right? js will return 021
return x.substr(0,x.length-2)+"."+x.substr(x.length-2);

When there’s a zero on the left, javascript goes nuts. An easy fix would be:

while (x.toString().substr(0,1) == "0")
    x=x.substr(1);

and problem solved!

References:

w3Schools

webmasterworld

jibbering

:, , , ,


No comments for this entry yet...

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!