The Netlobo logo - a Nevada desert landscape

Javascript Number Formatting

A collection of number formatting functions for javascript that are free to copy and use

Published Nov 16, 2007 by lobo235
Last updated on May 19, 2009

When displaying large numbers to your site visitors it is nice to format them so that they are easy to read. Using javascript you can format these numbers to make them look pretty or clean up a number that the user has entered in order to strip unwanted characters. There are a lot of things you can do to numbers with javascript but here are some of our favorite functions. These functions make use of regular expressions to do the heavy lifting. Toward the end of the article you will find a test page where you can test each function.

Formatting Numbers

The numberFormat() function takes any decimal number, negative or positive, and formats it by adding commas every three digits. This makes the number more readable for your site visitors:

// This function formats numbers by adding commas
function numberFormat(nStr){
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + ',' + '$2');
return x1 + x2;
}

Strip Non-Numeric Characters From a String

The stripNonNumeric() function strips any non-numeric characters from a string leaving you with a valid decimal number. This function considers the minus sign (hyphen) and the period to be numeric and will not strip them unless the minus sign is not at the beginning of the number or there is more than one period:

// This function removes non-numeric characters
function stripNonNumeric( str ){
str += '';
var rgx = /^\d|\.|-$/;
var out = '';
for( var i = 0; i < str.length; i++ ){
if( rgx.test( str.charAt(i) ) ){
if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
( str.charAt(i) == '-' && out.length != 0 ) ) ){
out += str.charAt(i);
}
}
}
return out;
}

Example

These functions work well together too. I like to use the stripNonNumeric function to remove unwanted characters first and then pass the resulting number to the numberFormat function to make it presentable to the user. In the following example you will be able to test each function out and also test how they work when used together. Here is the example: javascript number functions example

6 comments for this article.

Other great Web Development and Programming articles on Netlobo.com:
Javascript document.getElementsByClassName
Making AJAX Easier
Passing information from Javascript to PHP