Format Numbers Using Javascript
This is a great little function for formatting numbers with Javascript
Published Feb 7, 2007 by lobo235Last updated on Jul 3, 2007
When using JavaScript sometimes it is necessary to format numbers to make them more readable. For example, if you have a number like 741934950 it looks much better if it is formatted as 741,934,950. Doing the formatting in JavaScript can be more useful than doing it server-side because a lot of the time you don't want to deal with numbers that have commas in them on the server. The following is a JavaScript function that will let you easily format numbers by adding commas to them. You can also specify a prefix that will be placed at the beginning of your number. This is useful if you are dealing with currency because you can easily add the currency symbol for your country's currency.
// This function formats numbers by adding commas
function numberFormat(nStr,prefix){
var prefix = prefix || '';
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 prefix + x1 + x2;
}
Here are some examples of how to use the function:
- You want to format the number 5762325 so it is easier to read.
document.write( numberFormat( 5762325 ) );
- You want to format the number 5762325.2534 so it is easier to read.
document.write( numberFormat( 5762325.2534 ) );
As you can see, it works with decimals. - You want to format the number 5762325.25 as a US dollar amount.
document.write( numberFormat( 5762325.25, "$" ) );
These examples should be fairly easy to understand and the function should be fairly easy for you to implement on your pages.
0 comments for this article.
add this article to del.icio.us!
A DIV Border Using line.gif
Delete Confirmation using Javascript
CSS Tool-tips
