pnpm add decimal.js
unplugin-auto-import 配置:
AutoImport({
imports: [
{
"decimal.js": ['Decimal'],
}
],
dts: "src/auto-import.d.ts",
})
const num1 = new Decimal(123); // 从数字
const num2 = new Decimal('456.789'); // 从字符串(推荐)
const num3 = new Decimal(num2); // 从另一个 Decimal
const num4 = new Decimal('1e10'); // 科学计数法
最佳实践 :传入浮点数时建议使用字符串形式,避免 JavaScript 浮点精度问题。
const a = new Decimal('0.1');
const b = new Decimal('0.2');
const result = a.plus(b); // 结果: 0.3
console.log(result.toString()); // "0.3"
const a = new Decimal('10');
const b = new Decimal('3.7');
const result = a.minus(b); // 结果: 6.3
const a = new Decimal('12.5');
const b = new Decimal('4');
const result = a.times(b); // 结果: 50
const a = new Decimal('10');
const b = new Decimal('3');
const result = a.dividedBy(b); // 结果: 3.3333333333333333
const num = new Decimal('3.1415926');
num.toFixed(2); // "3.14" (四舍五入保留2位)
num.toFixed(4); // "3.1416"
num.toFixed(0); // "3"
const num = new Decimal('1234.5678');
num.precision(6); // "1234.57" (保留6位有效数字)
new Decimal('1.23').ceil().toNumber(); // 2
new Decimal('-1.23').ceil().toNumber(); // -1
new Decimal('1.99').floor().toNumber(); // 1
new Decimal('-1.99').floor().toNumber(); // -2
new Decimal('1.5').round().toNumber(); // 2
new Decimal('1.4').round().toNumber(); // 1
new Decimal('0.1').equals('0.1'); // true
new Decimal('0.1').equals(0.1); // true(注意:JavaScript 0.1 存在精度问题)
const a = new Decimal('10');
const b = new Decimal('5');
a.greaterThan(b); // true
const a = new Decimal('10');
const b = new Decimal('5');
a.lessThanOrEqualTo(b); // false
// 最大值
Decimal.max(new Decimal('10'), new Decimal('20'), new Decimal('15')); // Decimal(20)
// 最小值
Decimal.min(new Decimal('10'), new Decimal('20'), new Decimal('15')); // Decimal(10)
const num = new Decimal('123.456');
num.toNumber(); // 123.456(转换为原生数字)
num.toString(); // "123.456"
num.toFixed(2); // "123.46"(字符串形式)
num.toJSON(); // "123.456"(用于 JSON 序列化)
new Decimal('10').mod(new Decimal('3')).toNumber(); // 1
new Decimal('2').pow(10).toNumber(); // 1024
new Decimal('16').sqrt().toNumber(); // 4
new Decimal('-123').abs().toNumber(); // 123
new Decimal('123').negated().toNumber(); // -123