Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 827
Sai Avinash Avatar asked Nov 14 '13 14:11

Sai Avinash


2 Answers

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));
like image 143
kajojeq Avatar answered Sep 30 '22 07:09

kajojeq


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

like image 45
Dallas Avatar answered Sep 30 '22 07:09

Dallas