toPrecision Rounds To Significant Digits

toPrecision keeps a total digit count and switches to exponential notation when digits run out, while toFixed pins decimal places and never abbreviates.

JavascriptData Integrity

Code

javascriptsnippet
23 lines
const rate = 123.456;

// toPrecision 按有效数字取整:返回字符串,可能切到指数形式
console.log('toPrecision(6) :', rate.toPrecision(6));
console.log('toPrecision(4) :', rate.toPrecision(4));
console.log('toPrecision(2) :', rate.toPrecision(2)); // 有效位不够 -> 指数形式
console.log('toFixed(2)     :', rate.toFixed(2));        // 小数点后位数,不缩写

// 大数用 toPrecision 会进入指数;toFixed 保持定点
const big = 123456.789;
console.log('big toPrecision(3):', big.toPrecision(3));
console.log('big toFixed(1)    :', big.toFixed(1));

// 结果是字符串:继续算术要 Number() 转回
const rounded = Number(rate.toPrecision(4));
console.log('number after round:', rounded, typeof rounded);

// 超出范围抛 RangeError:有效数字 1-100,小数位 0-100
try {
  (1.5).toPrecision(0);
} catch (error) {
  console.log('toPrecision(0)    :', error.constructor.name);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

toPrecision(6) : 123.456
toPrecision(4) : 123.5
toPrecision(2) : 1.2e+2
toFixed(2)     : 123.46
big toPrecision(3): 1.23e+5
big toFixed(1)    : 123456.8
number after round: 123.5 number
toPrecision(0)    : RangeError

Inside the snippet

Module-level bindings hold the data — rate, big, rounded — with no function scope in between.

Points of care

  • Everything it calls is documented as part of the language core.

Putting it to use

Look for the toPrecision(6) :, toPrecision(4) :, toPrecision(2) : prefixes when the file runs; they tie each line to its step.

Core lines

const rounded = Number(rate.toPrecision(4));
const big = 123456.789;
const rate = 123.456;

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `rate`, `big`, `rounded`.