JavaScript equivalent to printf/String.Format

前端 未结 30 2401
囚心锁ツ
囚心锁ツ 2020-11-21 04:27

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

30条回答
  •  梦毁少年i
    2020-11-21 05:14

    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.round below).

    (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"
    

    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

    Quick tutorial on JS number formatting

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

提交回复
热议问题