JavaScript multiply not precise

The best solution would be to use toFixed(x), and set x a number of decimals that should always be more than the expected results decimals (I usually put 8 there).

But instead of hacking -as kirilloid-, you should convert the result back to number again, so that any unneeded decimals are removed. After that perform any formatting you like on the number.

So this would return the needed result:

var result = +(0.57 * 10000).toFixed(8)

result would be now 5700

The + in front, converts the string result of "toFixed" to a number again.

Hope that helped!

EDIT 2019:

It seems that we should not trust toFixed for this according to this:http://stackoverflow.com/questions/661562/how-to-format-a-float-in-javascript/661757#661757 Better to use something like the following:

function fixRounding(value, precision) {
    var power = Math.pow(10, precision || 0);
    return Math.round(value * power) / power;
}

var multiply = function(a, b) {
    var commonMultiplier = 1000000;

    a *= commonMultiplier;
    b *= commonMultiplier;

    return (a * b) / (commonMultiplier * commonMultiplier);
};

This works in a known range. Therefore, it might be a good idea to round the number to a decimal point smaller than commonMultiplier.

> multiply(3, .1)
< 0.3
> multiply(5, .03)
< 0.15

Your choices in Javascript (indeed, in most languages) are integers or floating point numbers. If you write "0.57" you are forcing it into the world of floating point, where accuracy is limited.

If you want absolute accuracy, you'll need to work exclusively in integers.