Search code examples
javascriptfloating-pointfixed-point

Restrict Float Precision in JavaScript


I'm working on a function in JavaScript. I take two variables x and y.

I need to divide two variables and display result on the screen:

x=9; y=110;
x/y;

then I'm getting the result as :

0.08181818181818181

I need to do it with using some thing like BigDecimal.js that I found in another post.

I want that result was shown as:

0.081


Solution

  • Try this it is rounding to 3 numbers after coma:

    (x/y).toFixed(3);
    

    Now your result will be a string. If you need it to be float just do:

    parseFloat((x/y).toFixed(3));