The Netlobo logo - a Nevada desert landscape

Comments for Javascript Number Formatting

< Back to the article

6 comments for this article.

RSS Feed Icon Subscribe to the comments for this article

Posted: 2008-01-31 13:13:01 by idenise
This is exactly what I was looking for except I can't figure out how to make it work. I've never encountered the innerHTML format so I'm off to google it. I need to put the results into a text box. Can that be done? Thanks in advance if you can!
Posted: 2008-01-31 13:15:37 by lobo235 - Netlobo Staff Member
idenise,

To put the number in a text box you would need to know the id of the text box and then do something like this:

document.getElementById('textboxid').value=numberFormat(12345);

Let us know if you need more help and thanks for stopping by the site!
Posted: 2008-06-25 09:48:03 by Jaganathan
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;
}
Posted: 2008-11-08 09:26:21 by RikArends
Hi,

Couldn't help it had to rewrite using proper regexp. These are functionally equivalent to your code including removing non-starting -'s and the . if there are more than 1:
This code is most likely a lot faster.

function numberFormat(s){
var r=[];
String(s).replace(/(\d{3})|(\..*)/g,function(m,a,x){r.push(r.length&&a?',':'',a?a:x)});
return r.join('');
}

function stripNonNumeric(s){
var d = 0;
return String(s).replace(/[^0-9.-]/g,'').replace(/(.+)\-/g,'$1').replace(/\./,function(m){return d++?'':m;});
}
Posted: 2009-01-23 09:24:39 by wilq32
RikArends function does not work (check many diffrent numbers), but intresetring idea :). Here is mine function with one line with defining limiter:

numberFormat = function (number,limiter)
{
return ((arguments[2] = number.toString().replace(new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),'$1'+limiter+'$2$3')) == number) ? arguments[2] : arguments.callee(arguments[2],limiter);
}

alert(numberFormat(423523452345,"."));
Posted: 2011-06-30 05:48:47 by KP
http://code.google.com/p/javascript-number-formatter/

Just created a project at Google code which supports common format like #,##0.00 or international number formatting like #’###.## or #,####.## or even reverse from common format #.###,##.

RSS Feed Icon Subscribe to the comments for this article

Post your comment for the Javascript Number Formatting article:

Name (required) (letters and numbers only):
Email (required) (will not be published):
Website (include http://):
Comment (required): (HTML tags allowed: pre, strong, em, b, i)