Search code examples
javascriptfloating-pointroundingdigitsdecimal

Using Math.round in javascript adds weird number of 0s at the end


Possible Duplicate:
Is JavaScript’s Math broken?

I'm using Math.round to round the number and for some reason it adds weird number of 0s at the end which should not be there. Here is my code:

return Math.round($digit * 1000) / 1000; 

i want numbers to have 3 decimal points

example:

  Math.round(29.469 * 1000) / 1000 = returns this value: 29.469000000000023 

cant seem to figure out why. is there a different way of rounding decimals to certain decimal point? i need 3 decimal points. Or maybe trim everything after third decimal digit? That would be perfect take the returned number and trim everything after third decimal.


Solution

  • yourVariable.toFixed(3);
    

    Will give you what you want.

    MDN docs