vote up 7 vote down star
1

I'm looking for a good Javascript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .NET).

My basic requirement is thousand seperator format for numbers for now, but something that handles lots of combinations (including dates) would be good.

I realise Microsoft's AJAX library provides a version of String.Format() but we don't want the entire overhead of that framework.

flag

5 Answers

vote up 7 vote down check

Try sprintf() for JavaScript.

link|flag
love it, works great. – Cheeso Dec 27 '09 at 23:43
vote up 2 vote down

I'll add my own discoveries which I've found since I asked:

Sadly it seems sprintf doesn't handle thousand seperator formatting like .NET's string format.

link|flag
vote up 1 vote down

Hi there,

There are "sprintf" for javascript which you can find it from here: http://www.webtoolkit.info/javascript-sprintf.html

Regards, Pooria.

link|flag
vote up 1 vote down

If you are looking to handle the thousands separator, you should really use toLocaleString() from the Javascript Number class since it will format the string for the user's region.

The Javascript Date class can format localized dates and times.

link|flag
It's actually a set by the user as a setting in the application (not the machine their on) but I'll take a look, thanks – Chris S Mar 4 '09 at 13:19
vote up 1 vote down

I use a small library called String.format for JavaScript which supports most of the format string capabilities (including format of numbers and dates), and uses the .NET syntax. The script itself is smaller than 4 kB, so it doesn't create much of overhead.

link|flag
I took a look at that library and it looks really great. I was pissed off when I saw that the download was an EXE. What the heck is that about? Didn't download. – jessegavin Apr 6 at 18:04

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.