JS: Format Number

By Xah Lee. Date: . Last updated: .

JavaScript does not have a “format” or “printf” function. The following code are solutions.

Number to String, Truncate Decimal

To show just n decimal places, use toFixed.

〔►see JS: Number.prototype.toFixed

To show just n significant digits, use toPrecision, but result may be in exponential notation.

〔►see JS: Number.prototype.toPrecision

Use toExponential to always return a string in exponential notation such as "3.12e+2" , then you can use regex to parse to a form you want.

〔►see JS: Number.prototype.toExponential

Format Number with Metric Prefix

function xah_format_number (n,m) {
    // format number with metric prefix such as 1.2k
    // n is integer. The number to be converted
    // m is integer. The number of decimal places to show. Default to 1.
    // returns a string, with possibly one of k M G T ... suffix.

    // http://xahlee.info/js/javascript_format_number.html
    // version 2017-03-28

    var prefix = ["", " k", " M", " G", " T", " P", " E", " Z", " Y", " * 10^27", " * 10^30", " * 10^33"]; // should be enough. Number.MAX_VALUE is about 10^308
    var ii = 0;
    var m = ( m === undefined ? 1 : m );
    while ((n = n/1000) >= 1) { ii++; }
    return (n * 1000).toFixed(m) + prefix[ii];
};

console.log(
 xah_format_number(111, 1) === "111.0"
); // true

console.log(
 xah_format_number(111222, 1) === "111.2 k"
); // true

console.log(
 xah_format_number(111222333, 1) === "111.2 M"
); // true

console.log(
 xah_format_number(111222333444, 1) === "111.2 G"
); // true

console.log(
 xah_format_number(111222333444) === "111.2 G"
); // true

console.log(
 xah_format_number(111222333444, 3) === "111.222 G"
); // true

console.log(
 xah_format_number(111222333444, 0) === "111 G"
); // true

Number Topic


  1. JS: Number Object
  2. JS: Number Constructor
  3. JS: Number.prototype

String Topic

  1. JS: Default Charset/Encoding
  2. JS: String Code Unit vs Code Point
  3. JS: Unicode Character Escape Sequence
  4. JS: Allowed Characters in Identifier
  5. HTML: Allowed Characters in id Attribute
  6. HTML: Character Sets and Encoding
  7. HTML/XML Entity List

  1. JS: Template String
  2. JS: Convert String to Number
  3. JS: Encode URL, Escape String
  4. JS: Format Number
  5. JS: JSON Object

  1. JS: String Object
  2. JS: String.prototype
  3. JS: String Constructor

RegExp Topic

  1. JS: RegExp Tutorial
  2. JS: String Methods for RegExp
  3. JS: RegExp Object
  4. JS: RegExp Constructor
  5. JS: RegExp.prototype
  6. JS: RegExp Syntax
Like what you read? Buy JavaScript in Depth