/    Sign up×
Community /Pin to ProfileBookmark

How Do You Format A Number(With Commas)

How can you format a number in Javascript to automatically place commas? As in a number greater than 1,000 will have commas correctly located whenever they are needed in the number.

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@phpnoviceJun 10.2005 — There is no supplied method for that. You have to conver the number to a string and insert the commas yourself.
Copy linkTweet thisAlerts:
@CharlesJun 10.2005 — <script type="text/javascript">

String.prototype.reverse = function () {return this.split('').reverse().join('')};

Number.prototype.withCommas = function () {
if (isNaN (this)) return NaN.toString();
var n = Math.abs(this).toFixed(2).split('.');
return [(this < 0 ? '-' : ''), (n[0].length > 4 ? n[0].reverse().match(/d{1,3}/g).join(',').reverse() : n[0]), n[1] > 0 ? '.' + n[1] : undefined].join('');
}

alert (Number(1234567890).withCommas())

</script>
Copy linkTweet thisAlerts:
@Sup3rkirbyauthorJun 11.2005 — Thank You very much for that function Charles.

One comment on it though. With any number less than ten-thousand, it does not insert the comma. But that is not a problem. Thanks again.
Copy linkTweet thisAlerts:
@A1ien51Jun 11.2005 — I think

....].length > 4 ? n[0......

Should be

....].length >= 4 ? n[0......

Eric
Copy linkTweet thisAlerts:
@CharlesJun 11.2005 — Thank You very much for that function Charles.

One comment on it though. With any number less than ten-thousand, it does not insert the comma. But that is not a problem. Thanks again.[/QUOTE]
The Sisters taught me in grade school, you don't use a comma if the number is less than 10,000.
×

Success!

Help @Sup3rkirby spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...