Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

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

You are here: irt.org | FAQ | JavaScript | Number | Q7 [ previous next ]

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

©2018 Martin Webb