UNPKG

656 BJavaScriptView Raw
1// Computes the decimal coefficient and exponent of the specified number x with
2// significant digits p, where x is positive and p is in [1, 21] or undefined.
3// For example, formatDecimal(1.23) returns ["123", 0].
4export default function(x, p) {
5 if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
6 var i, coefficient = x.slice(0, i);
7
8 // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
9 // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
10 return [
11 coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
12 +x.slice(i + 1)
13 ];
14}