JS: Number.prototype.toPrecision

By Xah Lee. Date: . Last updated: .
number.toPrecision(n)
  • Return a string representation of number, with n significant digits.
  • Result may be in exponential notation. e.g. "1e+1" meaning 1*10^1, or 10.
  • If n is undefined, call ToString instead.
console.assert(
 (3.123).toPrecision(1) ===
  "3",
);
console.assert(
 (3.123).toPrecision(2) ===
  "3.1",
);
console.assert(
 (3.123).toPrecision(3) ===
  "3.12",
);
console.assert(
 (3.123).toPrecision(4) ===
  "3.123",
);
console.assert(
 (3.123).toPrecision(5) ===
  "3.1230",
);
console.assert(
 (12.345).toPrecision(1) ===
  "1e+1",
);
console.assert(
 (12.345).toPrecision(2) ===
  "12",
);
console.assert(
 (12.345).toPrecision(3) ===
  "12.3",
);
console.assert(
 (0.123).toPrecision(1) ===
  "0.1",
);
console.assert(
 (0.123).toPrecision(2) ===
  "0.12",
);
console.assert(
 (0.123).toPrecision(3) ===
  "0.123",
);