пятница, 18 октября 2013 г.

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 be num.toFixed(2), which formats num to 2 decimal places, with rounding (but see @ars265's comment about Math.roundbelow).
12.345.toFixed(2); // returns "12.35" (rounding!)
12.3.toFixed(2); // returns "12.30" (zero padding)

Exponential form

The equivalent of sprintf("%.2e", num) is num.toExponential(2).
33333 .toExponential(2); // "3.33e+4"
//   ^ Note the space, which keeps the . from being a decimal point.
//     Leaving out the space is a syntax error :-(

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).
3735928559 .toString(16); // to base 16: "deadbeef"
parseInt("deadbeef", 16); // from base 16: 3735928559

Reference Pages

Mozilla reference page for toFixed() (with links to toPrecision(), toExponential(), toLocaleString(), ...)

Комментариев нет: