教程 decimaljs tutorial

科学计数法

decimal.js 提供 .toExponential() 方法,将 Decimal 实例转换为科学计数法字符串表示。

基本用法

js
import Decimal from 'decimal.js';

const num = new Decimal('123456789');
console.log(num.toExponential());       // 输出 "1.23456789e+8"
console.log(num.toExponential(3));      // 输出 "1.235e+8"

`

参数为可选的小数点后有效位数,默认为数字本身的所有有效位。

相关配置

  • Decimal.toExpNeg 和 Decimal.toExpPos 配置控制何时自动转换为科学计数法,超出范围自动使用科学计数法显示。
js
Decimal.set({ toExpNeg: -5, toExpPos: 10 });

console.log(new Decimal('0.000001').toString());  // 不使用科学计数法
console.log(new Decimal('1e+15').toString());     // 使用科学计数法

使用建议

  • 科学计数法适用于展示非常大或非常小的数值,避免字符串过长。
  • 结合 .toExponential() 可以灵活控制格式精度。

科学计数法输出方便阅读和传输,decimal.js 提供简单易用的方法满足各种格式化需求。