Restrict Float Precision in JavaScript

13,362

Solution 1

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));

Solution 2

You can do this

Math.round(num * 1000) / 1000

This will round it correctly. If you wish to just truncate rather than actually round, you can use floor() instead of round()

Solution 3

Use this to round 0.818181... to 0.81:

x = 9/110;
Math.floor(x * 1000) / 1000;

Solution 4

Try this

var num = x/y;
parseFloat((Math.round(num * 100) / 100).toPrecision(3))
Share:
13,362
Sai Avinash
Author by

Sai Avinash

Interested in all Microsoft technology stack

Updated on August 08, 2022

Comments

  • Sai Avinash
    Sai Avinash over 1 year

    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

  • Pointy
    Pointy over 10 years
    Yes but note that .toFixed() returns a string, not a number. May not matter here of course.
  • kajojeq
    kajojeq over 10 years
    Yes, I wonder now how it's matter if: var x = (9/110).toFixed(3); console.log(x); console.log(x*24); console.log(x/45); console.log(x--); all of this works even if it is string. When does it matter? Thanks
  • Smern
    Smern over 10 years
    @kajojeq, if you are doing like (9/110).toFixed(3) === 0.082 it will return false
  • kajojeq
    kajojeq over 10 years
    @smerny Yes you right. I am not often using === and == still gives true. thanks for fast reply!
  • Felix Kling
    Felix Kling over 10 years
    "When does it matter?" Try x + 42.
  • kajojeq
    kajojeq over 10 years
    Right, added line with parsing to float if needed. Hope now It's clear. thanks
  • Claies
    Claies almost 9 years
    You should be aware that this question is a year old, with an accepted answer and multiple possible duplicates. Therefore, you should take extra care to demonstrate how your answer is more useful than the already provided responses.