# Rounding Numbers to a given Decimal Point

For reasons that are beyond me, **Javascript does not have a function that could be used to round a number to a given decimal points**. If you want to show the price of an item in the format 5.00, you cannot just call a function round(5,2) to do it. Yes, Javascript has a rounding function - ** Math.round() - but that function just rounds the number to its nearest integer**. So, as always, I have created a function that will do this...

I have done many things that I hate to get this function to work - including **converting a number to a string**. Don't blame me - its the only way. So do not use the returned value for any calculation - use it for display only. If you must use it for calculation, convert it back to a number using the `Number()`

function.

```
/**
* Function that could be used to round a number to a given decimal points. Returns the answer
* Arguments : number - The number that must be rounded
* decimal_points - The number of decimal points that should appear in the result
*/
function roundNumber(number,decimal_points) {
if(!decimal_points) return Math.round(number);
if(number == 0) {
var decimals = "";
for(var i=0;i<decimal_points;i++) decimals += "0";
return "0."+decimals;
}
var exponent = Math.pow(10,decimal_points);
var num = Math.round((number * exponent)).toString();
return num.slice(0,-1*decimal_points) + "." + num.slice(-1*decimal_points)
}
//Usage
roundNumber(2.55343,2); //Returns 2.55
roundNumber(2.55843,2); //Returns 2.56
roundNumber(2,2); //Returns 2.00
roundNumber(0,2); //Returns 0.00
```

Is there a better way to do this? Preferably without using string operations?

blog comments powered by Disqus