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

Q7 How do you round a number to a X decimal places?

irt.org | Knowledge Base | JavaScript | Number | Q7 [ previous next ]

Q7 How do you round a number to a X decimal places?

<script language="JavaScript"><!--
function round(number,X) {
// rounds number to X decimal places, defaults to 2
    X = (!X ? 2 : X);
    return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

document.write(round(1,2)+'<BR>');
document.write(round(1.2,2)+'<BR>');
document.write(round(1.23,2)+'<BR>');
document.write(round(1.234,2)+'<BR>');
document.write(round(1.2345)+'<BR>');
//--></script>

The previous code won't work on large floating point numbers. You will need to convert the number to a string and then perform parsing on that. If users have a very recent browser you can use the toFixed() function:

if(!Number.prototype.toFixed) {
  //alternative string parsing functionality or bail out
}
else {
  y = x.toFixed(r);
  // x is your number and r is number of places
}

Feedback on 'Q7 How do you round a number to a X decimal places?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


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