Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round a number in JavaScript?

While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of

Name : Value Name2 : Value2 

etc.

The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?

like image 651
Ace Avatar asked Oct 29 '08 09:10

Ace


People also ask

How do you round a number in JavaScript?

The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).

How do you round a number to 2 decimal places in JavaScript?

Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.

How do you round to 5 in JavaScript?

To round a number to the nearest 5, call the Math. round() function, passing it the number divided by 5 and multiply the result by 5 .

How do you round the number 7.25 to the nearest integer in JavaScript?

The Math. round() function in JavaScript is used to round the number passed as parameter to its nearest integer. Parameters : The number to be rounded to its nearest integer.


1 Answers

If you need to round to a certain number of digits use the following function

function roundNumber(number, digits) {             var multiple = Math.pow(10, digits);             var rndedNum = Math.round(number * multiple) / multiple;             return rndedNum;         } 
like image 149
Raj Rao Avatar answered Sep 28 '22 18:09

Raj Rao