JS: Format Number

By Xah Lee. Date: . Last updated: .

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

Show Only N Decimal Places

Use toFixed.

[see JS: Number.prototype.toFixed]

Show Only N Significant Digits

Use toPrecision, but result may be in exponential notation.

[see JS: Number.prototype.toPrecision]

Show in Exponential Notation

Use toExponential

Example output: "3.12e+2"

[see JS: Number.prototype.toExponential]

Format Number with Metric Prefix

const xah_format_number = ((n, m = 1) => {
/* [
format number with metric prefix, example: 1.2 k
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 2019-04-15
 ] */
    const 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
    let ii = 0;
    while ((n = n/1000) >= 1) { ii++; }
    return (n * 1000).toFixed(m) + prefix[ii];
});

// --------------------------------------------------
// test

console.log(
 xah_format_number(111, 1) === "111.0"
&&
 xah_format_number(111222, 1) === "111.2 k"
&&
 xah_format_number(111222333, 1) === "111.2 M"
&&
 xah_format_number(111222333444, 1) === "111.2 G"
&&
 xah_format_number(111222333444) === "111.2 G"
&&
 xah_format_number(111222333444, 3) === "111.222 G"
&&
 xah_format_number(111222333444, 0) === "111 G"
); // true

JS Number

  1. Format Number
  2. String to Number
  3. Random Number

JS String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Codepoint
  4. String Escape Sequence
  5. Unicode Escape Sequence

JS RegExp

  1. RegExp Tutorial
  2. RegExp Syntax
  3. Regex Find/Replace

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. CSS
  3. JavaScript
  4. JS Obj Ref
  5. DOM
  6. SVG
  7. Blog