How number is treated in JavaScript? JavaScript is loosely typed and the plus operator also concatenates, you can easily convert JavaScript Numbers to Strings similar to this: 1 + “”, but as we all know that JavaScript doesn’t have many built-in methods to format numbers. Most of the time we need to write our customized code to do it.The following is 6 very useful JavaScript number format function,why have to re-inventing the wheel? Don’t waste your valuable time to write it by yourself, only copy which you like and use it!
Of course if you had wrote your proudly number format function,don’t only stock in your hard disk( or your head), let’s share!
No.1 by Matt:
Basically, you can pass in a String as the format that contain any one number,and the result will replace the number in the format String with the properly formatted Number object. See the comment block for details.
- /**
- * Formats the number according to the ‘format’ string;
- * adherses to the american number standard where a comma
- * is inserted after every 3 digits.
- * note: there should be only 1 contiguous number in the format,
- * where a number consists of digits, period, and commas
- * any other characters can be wrapped around this number, including ‘$’, ‘%’, or text
- * examples (123456.789):
- * ‘0′ - (123456) show only digits, no precision
- * ‘0.00′ - (123456.78) show only digits, 2 precision
- * ‘0.0000′ - (123456.7890) show only digits, 4 precision
- * ‘0,000′ - (123,456) show comma and digits, no precision
- * ‘0,000.00′ - (123,456.78) show comma and digits, 2 precision
- * ‘0,0.00′ - (123,456.78) shortcut method, show comma and digits, 2 precision
- *
- * @method format
- * @param format {string} the way you would like to format this text
- * @return {string} the formatted number
- * @public
- */
- Number.prototype.format = function(format) {
- if (! isType(format, ’string’)) {return ”;} // sanity check
- var hasComma = -1 < format.indexOf(’,'),
- psplit = format.stripNonNumeric().split(’.'),
- that = this;
- // compute precision
- if (1 < psplit.length) {
- // fix number precision
- that = that.toFixed(psplit[1].length);
- }
- // error: too many periods
- else if (2 < psplit.length) {
- throw(’NumberFormatException: invalid format, formats should have no more than 1 period: ‘ + format);
- }
- // remove precision
- else {
- that = that.toFixed(0);
- }
- // get the string now that precision is correct
- var fnum = that.toString();
- // format has comma, then compute commas
- if (hasComma) {
- // remove precision for computation
- psplit = fnum.split(’.');
- var cnum = psplit[0],
- parr = [],
- j = cnum.length,
- m = Math.floor(j / 3),
- n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop
- // break the number into chunks of 3 digits; first chunk may be less than 3
- for (var i = 0; i < j; i += n) {
- if (i != 0) {n = 3;}
- parr[parr.length] = cnum.substr(i, n);
- m -= 1;
- }
- // put chunks back together, separated by comma
- fnum = parr.join(’,');
- // add the precision back in
- if (psplit[1]) {fnum += ‘.’ + psplit[1];}
- }
- // replace the number portion of the format with fnum
- return format.replace(/[\d,?\.?]+/, fnum);
- };
I noticed that some countries (e.g. Netherlands) use the comma and period exactly opposite (e.g. 1.234,56 instead of 1,234.45) ,but it can be easily modified.
No.2 by Mredkj (Add commas)
- function addCommas(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;
- }
No.3 by netlobo(Strip Non-Numeric Characters From a String)
This 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;
- }
No.4 by Stephen Chapman
With this function,we can easily select different formatting by changing the values in the second through eighth parameters. The second parameter is the number of decimal places that the number should have.
- // number formatting function
- // copyright Stephen Chapman 24th March 2006, 10th February 2007
- // permission to use this function is granted provided
- // that this copyright notice is retained intact
- function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2)
- {
- var x = Math.round(num * Math.pow(10,dec));
- if (x >= 0) n1=n2='';
- var y = (''+Math.abs(x)).split('');
- var z = y.length - dec;
- if (z<0) z--;
- for(var i = z; i < 0; i++)
- y.unshift('0');
- y.splice(z, 0, pnt);
- if(y[0] == pnt) y.unshift('0');
- while (z > 3)
- {
- z-=3;
- y.splice(z,0,thou);
- }
- var r = curr1+n1+y.join('')+n2+curr2;
- return r;
- }
No.5 by java-scripts
This function formats a numeric value passed in to it with specified number of decimal values. Numeric value will not be rounded.
- function format_number(pnumber,decimals){
- if (isNaN(pnumber)) { return 0};
- if (pnumber=='') { return 0};
- var snum = new String(pnumber);
- var sec = snum.split('.');
- var whole = parseFloat(sec[0]);
- var result = '';
- if(sec.length > 1){
- var dec = new String(sec[1]);
- dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals)));
- dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals));
- var dot = dec.indexOf('.');
- if(dot == -1){
- dec += '.';
- dot = dec.indexOf('.');
- }
- while(dec.length <= dot + decimals) { dec += '0'; }
- result = dec;
- } else{
- var dot;
- var dec = new String(whole);
- dec += '.';
- dot = dec.indexOf('.');
- while(dec.length <= dot + decimals) { dec += '0'; }
- result = dec;
- }
- return result;
- }
No.6 by geocities
This function formats a number with a number of decimal places from 0 to 3.
- function formatNumber (obj, decimal) {
- //decimal - the number of decimals after the digit from 0 to 3
- //-- Returns the passed number as a string in the xxx,xxx.xx format.
- anynum=eval(obj.value);
- divider =10;
- switch(decimal){
- case 0:
- divider =1;
- break;
- case 1:
- divider =10;
- break;
- case 2:
- divider =100;
- break;
- default: //for 3 decimal places
- divider =1000;
- }
- workNum=Math.abs((Math.round(anynum*divider)/divider));
- workStr=""+workNum
- if (workStr.indexOf(".")==-1){workStr+="."}
- dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
- pStr=workStr.substr(workStr.indexOf("."))
- while (pStr.length-1< decimal){pStr+="0"}
- if(pStr =='.') pStr ='';
- //--- Adds a comma in the thousands place.
- if (dNum>=1000) {
- dLen=dStr.length
- dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
- }
- //-- Adds a comma in the millions place.
- if (dNum>=1000000) {
- dLen=dStr.length
- dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
- }
- retval = dStr + pStr
- //-- Put numbers in parentheses if negative.
- if (anynum<0) {retval="("+retval+")";}
- //You could include a dollar sign in the return value.
- //retval = "$"+retval
- obj.value = retval;
- }

April 25th, 2008
Ntt.cc 








Posted in
Tags: 
RSS Feed
Email Feed
Is there any way to copy these functions without copying the line numbers? The line numbers might look super extra dope and sweet, but the code can’t be copied and used.
@RT
I reset the option,u can download them by click “Download XXXXX.js” above.
function formatWithComma(number) {
var formattedNumberString = (number%1000).toString();
var x = parseInt(number/1000);
while(x > 0) {
formattedNumberString = x%1000 + ‘,’ + formattedNumberString;
x = parseInt(x/1000);
}
return formattedNumberString;
}
function addCommas(input) {
var Rez = new String(input);
Rez = Rez.replace(/\./,”@”);
Rez = Rez.replace(/\,/g,”.”);
Rez = Rez.replace(/\@/,”,”);
return Rez;
The “@” character can be any character, except comma and period.
thank you
note. The script number 4 by Stephen Chapman are faulty.
if you enter 0,0xxx the value are formatted to 00x,xx
It works if you enter x,xx / 0,00xxx
pretty solution! it’s seems I have a another choose.
i think it will be more helpfull if you include the example all the html with one compressed file to download
The No.2 does not work unless the regex is change to this:
var rgx = /(\d+)(\d{3}),?/;
Without the last /,?/ the loop runs only once.
[...] Great list of javascript functions for number formatting. [...]
[...] via 6 very basic but very useful JavaScript Number Format Functions for web developers – Ntt.cc. [...]
number_format = function(number, decimalCount, decimalSeparator, thousandSeparator)
{
if(isNaN(parseInt(number))) return null;
decimalCount = (!isNaN(parseInt(decimalCount))) ? decimalCount : 0;
decimalSeparator = (typeof(decimalSeparator) == ’string’) ? decimalSeparator : ‘.’;
thousandSeparator = (typeof(decimalSeparator) == ’string’) ? thousandSeparator : ”;
integerValue = parseInt(Math.abs(number));
DecimalValue = number – integerValue;
integerValueArray = integerValue.toString().replace(/^\s+/,”").split(”);
integerValueOutputArray = new Array();
integerValueOutputArrayReverse = new Array();
var x = 0;
for (var i = integerValueArray.length; i > 0; –i) {
x++;
if((x-1) && (x-1)%3 == 0)
{
integerValueOutputArrayReverse.push(thousandSeparator)
}
integerValueOutputArrayReverse.push(integerValueArray[i-1]);
}
for (var i = integerValueOutputArrayReverse.length-1; i >=0 ; –i)
{
integerValueOutputArray.push(integerValueOutputArrayReverse[i]);
}
decimalValueArray = DecimalValue.toString().replace(/\s+$/,”").split(”);
decimalValueOutputArray = new Array();
for (var i = 2; i = decimalCount) break;
if((i-2) && (i-2)%3 == 0) {
decimalValueOutputArray.push(thousandSeparator)
}
decimalValueOutputArray.push(decimalValueArray[i]);
}
formatedNumber = integerValueOutputArray.join(”);
if(decimalValueOutputArray.length) {
formatedNumber += decimalSeparator + decimalValueOutputArray.join(”);
}
return formatedNumber;
}