This function assumes what is being submitted to it is a string, with a decimal point and two places after the decimal. To get your number into that format first, use this.
Then this function will properly comma separate the number. For example, 2345643.00 will return 2,345,643.00
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3) {
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
is there something like this for PHP?
http://us3.php.net/manual/en/function.number-format.php
number_format();
Ohhh.. Wonderful code snippet. Searching for long time.
this is how I do it:
function addCommas(nStr)
{
nStr += ”;
var x = nStr.split(‘.’);
var x1 = x[0];
var x2 = x.length > 1 ? ‘.’ + x[1] : ”;
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, ‘$1’ + ‘,’ + ‘$2’);
}
return x1 + x2;
}
Jack you function is much better thx. The function from the post is riddled with errors.
How about this script.
Any chance to insert a comma or a space between the numbers in this counter?
kasa=new Date(2008 ,12 ,60 ,30 ,01);
setInterval(function(){
with(Math){
var w=floor(((new Date())-kasa)/1000),lr,dr,mr,
l=floor(w/31536000),d=floor((lr=w%31536000)/86400),
g=floor((dr=lr%86400)/3600),m=floor((mr=dr%3600)/60),
s=floor(mr%60);
document.getElementById(‘money’).innerHTML=
(l?l+’ l., ‘:”)+d+’ dni,’+g+’ godz., ‘
+m+’ min., ‘+s+’ sek.’;
}
},1000);
setInterval(function(){
document.getElementById(‘MoneyCounter’).innerHTML=
((new Date())-kasa);
},130);
Here’s the same thing in 1 line. If anybody can do better, do share.
Can’t do better making it shorter, but I can fix it so it takes numeric arguments!
function commas(str) {
return (str+””).replace(/.(?=(?:.{3})+$)/g, ‘$&,’);
}
Hmm… and make it handle decimals in a hackish way. ;-)
function commas(str) {return (str+””).replace(/.(?=(?:[0-9]{3})+\b)/g, ‘$&,’);
function format(input)
{
var num=input.value.replace(/[^\d]/g,”);
if(num.length>3)
num = num.replace(/\B(?=(?:\d{3})+(?!\d))/g, ‘-‘);
input.value=num;
}
Hello Chris,
If amount will be 2200 then your var “d” will give an error as undefined variable and script will not execute this script only work when your amount is 2200.00 so I have edited your script and used it in my website ;) below is revised code which might solve this issue.
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) {
return '';
}
var minus = '';
if(i < 0) {
minus = '-';
}
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3) {
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) {
a.unshift(n);
}
n = a.join(delimiter);
if(d) {
if(d.length < 1) {
amount = n;
} else {
amount = n + '.' + d;
}
} else {
amount = n + ".00"
}
amount = minus + amount;
return amount;
}
God bless “.toLocaleString()”
@Yashar Imanlou: unfortunately the method toLocaleString isn’t widely supported yet, see http://caniuse.com/#search=locale.
I want to use it in html how can i add this
document.getElementById(“demo”).innerHTML = commer();
Or to use documen.wrte = “12,345”;
I need to make something like this 12345 to 12,345
numeral.js ( http://numeraljs.com )
This one seems the simplest / quickest…
function commas(str) {
return str.replace(/.(?=(?:.{3})+$)/g, ‘$&,’);
}
But, don’t laugh please… I freely admit I’m not a programmer. Just trying to do a simple change on a page — adding commas. Been playing with this for 40 minutes and not getting it.
I’m trying to get a variable I’ve calculated and use on the page (“calculatedHours”) to display with commas. Had NO clue it was this big of a deal…
Anyway, explaining it like I’m a 6 year old… Where would I plug this into the function?
I thought it would be:
function commas(calculatedHours) {
return str.replace(/.(?=(?:.{3})+$)/g, ‘$&,’);
}
and then
document.write(calculatedHours)
But no…. what do I replace to get it to display the variable calculatedHours with the commas???
Man….this is frustrating. I’ve played with content (HTML) on my page before, and thought throwing in a few lines of Java wouldn’t be too tough. It’s crazy tough. I never would’ve taken it on – I outsource any design (etc), but the time it’s taken to make a simple page has been astounding.
Still stuck. All I want to do is have it display a few numbers with commas for ease of reading. There’s a variable (a couple, actually, but I’m hoping if I get the method down I can repeat it).
Here’s the section (I AM ADDING SPACES WITHIN THE WORD S C R I P T SO IT WILL DISPLAY HERE – THAT’S THE ONLY DIFFERENCE)
< s c r i p t >
document.write(“As of today, “)
document.write(calculatedHours)
document.write(” hours have passed…”)
< / s c r i p t >
It outputs:
As of today, 3965 hours have passed…
I want it to output:
As of today, 3,965 hours have passed…
IS THERE REALLY NO SIMPLE WAY TO DO SOMETHING THIS SEEMINGLY SIMPLE????
Every piece of code I copy over doesn’t work… I’m sure there’s some “of course” stuff I’m missing, and the fault is mine for not knowing, but can anyone give me a few lines of code to accomplish this?
Thanks
Can anyone take a quick crack at this?
Still trying to do something that seems like it should be simple…
I’ve calculated a variable (“calculatedHours”), trying to get it to display with commas.
I thought it would be:
function commas(calculatedHours) {
return str.replace(/.(?=(?:.{3})+$)/g, ‘$&,’);
}
and then
document.write(calculatedHours)
…. not working. Anyone see the problem / can anyone post a couple lines of code that would work?
Thanks….
Never mind.
Here’s what works, for others who may come across this page / question:
<
script type=”text/javascript”>
function numberWithCommas(x) { // Zamaria
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, “,”);
}
document.write(numberWithCommas(calculatedHours))
I use this function to generate a constantly increasing number within a div element. http://jsfiddle.net/obysrnm2/
Does anyone have any suggestions for combining the generator with the separator. My implementations seem to return with error.
**sign**… N00bs…
"1,234,567,890"
All of this is wrong concept. In general, programmer/developer should not “format” the numbers.
The right concept:
Client side (browser), should read “regional settings” from the OS, and format the numbers according that. This should happens primary in “input” fields as well as in inline text wrapped with some tag.
Ex:
<number>123456</number> => 123.456
<number decimals="2">123456789E-4</number> => 12.345,68
Absolutely agree! I’m not new to programming, but I’m to web programming. And couldn’t believe that something so trivial and so widely needed is not solved! For (pretty big) project we are working on, best solution we came with was to use jQuery input masks (https://github.com/RobinHerbots/Inputmask)
Any reason not to just use number.toLocaleString()? It allows you to set your own delimiters, etc., but but default it just returns the number as a string with commas added in the right places.
Javascript has a method called toFixed() that will format your numbers so they have commas and even let you add 2 decimals. So if you have a number like 12345678.90, .toFixed() will convert it to 12,345,678.90. See https://www.w3schools.com/jsref/jsref_tofixed.asp for how to use it.
What about using numObj.toLocaleString()?
Javascript now supports the toLocaleString() Method which means you don’t need your code snippet. Sorry! Nice code tho