I\'m looking for a good JavaScript equivalent of the C/PHP printf()
or for C#/Java programmers, String.Format()
(IFormatProvider
for .
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:
The equivalent of sprintf("%.2f", num)
in JavaScript seems to be num.toFixed(2)
, which formats num
to 2 decimal places, with rounding (but see @ars265's comment about Math.round
below).
(12.345).toFixed(2); // returns "12.35" (rounding!)
(12.3).toFixed(2); // returns "12.30" (zero padding)
The equivalent of sprintf("%.2e", num)
is num.toExponential(2)
.
(33333).toExponential(2); // "3.33e+4"
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).
(3735928559).toString(16); // to base 16: "deadbeef"
parseInt("deadbeef", 16); // from base 16: 3735928559
Quick tutorial on JS number formatting
Mozilla reference page for toFixed() (with links to toPrecision(), toExponential(), toLocaleString(), ...)