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 a thousand separator format for numbers for now, but something that handles lots of combinations (including dates) would be good.
I realize Microsoft's Ajax library provides a version of String.Format()
, but we don't want the entire overhead of that framework.
I did not see the
String.format
variant:I didn't see pyformat in the list so I thought I'd throw it in:
Number Formatting in JavaScript
I got to this question page hoping to find how to format numbers in JavaScript, without introducing yet another library. Here's what I've found:
Rounding floating-point numbers
The equivalent of
sprintf("%.2f", num)
in JavaScript seems to benum.toFixed(2)
, which formatsnum
to 2 decimal places, with rounding (but see @ars265's comment aboutMath.round
below).Exponential form
The equivalent of
sprintf("%.2e", num)
isnum.toExponential(2)
.Hexadecimal and other bases
To print numbers in base B, try
num.toString(B)
. JavaScript supports automatic conversion to and from bases 2 through 36 (in addition, some browsers have limited support for base64 encoding).Reference Pages
Quick tutorial on JS number formatting
Mozilla reference page for toFixed() (with links to toPrecision(), toExponential(), toLocaleString(), ...)
I want to share my solution for the 'problem'. I haven't re-invented the wheel but tries to find a solution based on what JavaScript already does. The advantage is, that you get all implicit conversions for free. Setting the prototype property $ of String gives a very nice and compact syntax (see examples below). It is maybe not the most efficient way, but in most cases dealing with output it does not have to be super optimized.
Here are a few examples:
There is "sprintf" for JavaScript which you can find at http://www.webtoolkit.info/javascript-sprintf.html.
For basic formatting: