Home > Abakada: Back to Basics > Basic Scripting > Data Entry Validation > Rounding a number to n decimals
Abakada ~ Back to Basics
If you always want to round to two decimals use a function like
function round2 ( n ) {
n = Math.round ( n * 100 ) / 100;
n = ( n + 0.001 ) + '';
return n.substring ( 0, n.indexOf ( '.' ) + 3 );
}
which converts a given number into a string that is formatted as intended. Calling parseFloat on the result easily converts the output to a floating-point number, if needed. To check:
Now, using the above function plus the function below, we can format a number to a currency value:
function currency ( n, d ) {
n = round2 ( n, d );
for ( var i = n.indexOf ( '.' ) - 3; i > 0; i -= 3 )
n = n.substring ( 0, i ) + ', ' + n.substring ( i );
return n;
}
Note that the currency converter above expects a valid string value that can be converted to a number specifically, can contain only digits and decimals, and not commas or other characters. If so, the function returns NaN ( not a number ).
In actual use, the value to convert is typically passed from user input in a field that has already been validated for numeric entries only.
If you need to round to a varying number of decimal places, use the below function instead.
function roundn ( n, d ) {
n = n - 0;
d = d == void ( 0 ) ? 2 : d
var f = Math.pow ( 10, d );
n = Math.round ( n * f ) / f;
n += Math.pow ( 10, - ( d + 1 ) );
n += '';
return d == 0 ? n.substring ( 0, n.indexOf ( '.' ) ) :
n.substring ( 0, n.indexOf ( '.' ) + d + 1 );
}
which takes a number to round as the first argument, and an optional second argument to specify the number of decimals needed. To check:
Also note that starting with IE5.5 and NN6, there is a toFixed method for numbers which essentially does the above function.
var n = 2;
alert ( n.toFixed ( 2 ) )
If you would like to have the same functionality in IE4/5 and Netscape 4, this can be done by prototyping the Number object as follows:
if ( typeof ( Number ) !='undefined' &&
typeof ( Number.prototype ) !='undefined' ) {
if ( typeof ( Number.prototype.toFixed ) =='undefined' ) {
function Number_toFixed ( d ) {
var n = this
d = d==void ( 0 ) ? 2 : d
var f = Math.pow ( 10, d );
n = Math.round ( n * f ) / f;
n += Math.pow ( 10, - ( d + 1 ) );
n += '';
return d == 0 ? n.substring ( 0, n.indexOf ( '.' ) ) :
n.substring ( 0, n.indexOf ( '.' ) + d + 1 );
}
Number.prototype.toFixed = Number_toFixed;
}
}
You can then use toFixed in IE 4/5 and Netscape 4 in the same manner as in IE 5.5 and NN6.
Validating Against a Data Type ( Web Forms ) Web Forms Validation