JS: Format Number
JavaScript does not have a “format” or “printf” function. The following code are solutions.
Show Only N Decimal Places
Use toFixed
.
〔see Number.prototype.toFixed〕
Show Only N Significant Digits
Use toPrecision
, but result may be in exponential notation.
Show in Exponential Notation
Use toExponential
Example output: "3.12e+2"
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", );