实现说明
顶层就这几处状态:rate、big、rounded。
使用要点
- 跑完文件,输出里会留下标记——
toPrecision(6) :、toPrecision(4) :、toPrecision(2) :。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 状态都挂在模块顶层:rate、big、rounded。
核心语句
const rounded = Number(rate.toPrecision(4));
const big = 123456.789;
const rate = 123.456;
代码示例
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);
}