formatDecimal.js 843 B

1234567891011121314151617181920
  1. export default function(x) {
  2. return Math.abs(x = Math.round(x)) >= 1e21
  3. ? x.toLocaleString("en").replace(/,/g, "")
  4. : x.toString(10);
  5. }
  6. // Computes the decimal coefficient and exponent of the specified number x with
  7. // significant digits p, where x is positive and p is in [1, 21] or undefined.
  8. // For example, formatDecimalParts(1.23) returns ["123", 0].
  9. export function formatDecimalParts(x, p) {
  10. if (!isFinite(x) || x === 0) return null; // NaN, ±Infinity, ±0
  11. var i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e"), coefficient = x.slice(0, i);
  12. // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
  13. // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
  14. return [
  15. coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
  16. +x.slice(i + 1)
  17. ];
  18. }