Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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?

irt.org | Knowledge Base | JavaScript | Date | Q1494 [ previous next ]

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?

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>

Feedback on '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?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.