Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can any one suggest a good math function in javascript to round integer?

i have to round the value from 2.3456789 to 2.345 .

After . there must be three number only remaining should be removed

like image 989
user737767 Avatar asked Dec 11 '25 09:12

user737767


2 Answers

Use Math.round().

This will round to 3 decimal places.

var result=Math.round(2.3456789*1000)/1000  //returns 2.345  

In fact, the formula to round any number to x decimal points is:

1) Multiple the original number by 10^x (10 to the power of x).
2) Apply Math.round() to the result.
3) Divide result by 10^x.

like image 92
Saurabh Gokhale Avatar answered Dec 12 '25 22:12

Saurabh Gokhale


Javascript 1.5+ introduced Number.toFixed(n) and Number.toPrecision(n) - pick one depending on what you need.

Number.toFixed() lets you specify the number of digits after the decimal point (padded if necessary).

(2.3456789).toFixed(3) = "2.346"
(3).toFixed(3) = "3.000"

Number.toPrecision() lets you specify the number of significant figures.

(2.3456789).toPrecision(4) = "2.346"
like image 33
Andy Avatar answered Dec 12 '25 23:12

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!