JS: Format Number
JavaScript does not have a “format” or “printf” function. The following code are solutions.
Show Only N Decimal Places
Show Only N Significant Digits
Show in Scientific Notation
Format with Separator
e.g. 123,456.789
Format Number with Metric Prefix
const xah_format_number = ((n, m = 1) => { /* format number with metric prefix, e.g. 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/js_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", );
JavaScript, Number
- JS: Number
- JS: Assignment Operators
- JS: Math Operators
- JS: Number Comparison Operators
- JS: Convert String, Number
- JS: Convert Decimal, Hexadecimal
- JS: Convert Decimal, Binary
- JS: Format Number
- JS: Random Integer Range Function 💠
- JS: Number (class)
- JS: Number Constructor
- JS: Number.prototype
- JS: Math (namespace)