教程 decimaljs tutorial

转字符串格式

decimal.js 提供丰富的字符串转换方法,方便将高精度数值以不同格式输出。

常用方法

  • .toString()
    返回常规的字符串表示,自动根据数值大小决定是否使用科学计数法。

  • .toFixed(dp)
    按固定小数位数输出字符串,参数 dp 为小数位数。

  • .toDecimalPlaces(dp)
    四舍五入后返回字符串,保留指定小数位数。

  • .toExponential(dp)
    以科学计数法形式返回字符串,dp 指定小数点后位数。

  • .toSignificantDigits(sd)
    保留指定有效数字位数后返回字符串。

使用示例

js
import Decimal from 'decimal.js';

const num = new Decimal('1234.56789');

console.log(num.toString());          // "1234.56789"
console.log(num.toFixed(2));           // "1234.57"
console.log(num.toDecimalPlaces(3));  // "1234.568"
console.log(num.toExponential(2));    // "1.23e+3"
console.log(num.toSignificantDigits(4)); // "1235"

`

注意事项

  • .toFixed() 和 .toDecimalPlaces() 都会执行四舍五入。
  • 科学计数法适合非常大或非常小的数值展示。
  • 合理选择转换方法可满足不同格式输出需求。

通过灵活使用字符串转换方法,你可以根据需要精准控制数值的显示格式。