Question

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

Was it helpful?

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

OTHER TIPS

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

Use this to round 0.818181... to 0.81:

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

Try this

var num = x/y;
parseFloat((Math.round(num * 100) / 100).toPrecision(3))

if i'm use the simple expression, result may be unexpected:

const fraction = (value) => {
  return value - Math.floor(value);
}
fraction(1 / 3);
=> 0.333333333333 // is Right
fraction(22 / 3);
=> 0.33333333333333304 // is Unexpected

So, my robust expression is:

const fraction = (value) => {
  return parseFloat(value.toString().replace(/^\d+$/, '0').replace(/^.+?(?=\.)/, ''))
}
fraction(22 / 3);
=> 0.333333333333333
fraction(1111)
=> 0
fraction(.122211)
=> 0.122211
fraction(11111.122211)
=> 0.122211
fraction(11111.12)
=> 0.12
fraction(11111.11112)
=> 0.11112
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top