#

# Q1494 How can I round numbers with the decimal accuracy specify, correctly. When using Math.ceil it rounds always upwards i.e. 123.1234 (3 decimals) rounds to 123.124 although it shoud be 123.123?

You are here: irt.org | FAQ | JavaScript | Date | Q1494 [ previous next ]

Try:

```<script language="JavaScript"><!--
function round (n, d) {
n = n - 0; // force number
if (d == null) d = 2;
var f = Math.pow(10, d);
n += Math.pow(10, - (d + 1)); // round first
n = Math.round(n * f) / f;
n += Math.pow(10, - (d + 1)); // and again
n += ''; // force string
return d == 0 ? n.substring(0, n.indexOf('.')) :
n.substring(0, n.indexOf('.') + d + 1);
}

document.write('<pre>');
document.write('<br>0.5005 (3):'+round(0.5005,3))
document.write('<br>0.50051(3):'+round(0.50051,3))
document.write('<br>0.5009 (3):'+round(0.5009,3))
document.write('<br>0.50091(3):'+round(0.50091,3))
document.write('<br>0.59   (2):'+round(0.59,2))
document.write('<br>0.591  (2):'+round(0.591,2))
document.write('<br>0.59   (1):'+round(0.59,1))
document.write('<br>0.591  (1):'+round(0.591,1))
document.write('<br>2.9    (0):'+round(2.9, 0));
document.write('<br>2      (5):'+round(2, 5));
document.write('<br>2.1245 (3):'+round(2.1245, 3));
//--></script>```