写 Node.js 中处理 0.04f 精度的代码示例。这通常涉及货币计算或需要精确小数运算的场景。
JavaScript
复制
/** * Node.js 0.04f 精度处理方案 * 使用 decimal.js 或原生 BigInt 实现精确计算 */ // ============ 方案 1: 使用 decimal.js (推荐) ============ const Decimal = require('decimal.js'); // 配置精度 Decimal.set({ precision: 20, rounding: Decimal.ROUND_HALF_UP }); class PrecisionCalculator { constructor(precision = 2) { this.precision = precision; this.factor = new Decimal(10).pow(precision); } // 将数字转换为指定精度 toFixed(num) { return new Decimal(num).toFixed(this.precision); } // 加法 add(a, b) { return new Decimal(a).plus(b).toFixed(this.precision); } // 减法 subtract(a, b) { return new Decimal(a).minus(b).toFixed(this.precision); } // 乘法 multiply(a, b) { return new Decimal(a).times(b).toFixed(this.precision); } // 除法 divide(a, b) { return new Decimal(a).dividedBy(b).toFixed(this.precision); } // 0.04f 精度舍入 roundTo004(value) { // 以 0.04 为步长进行舍入 const step = new Decimal('0.04'); const val = new Decimal(value); const divided = val.dividedBy(step); const rounded = divided.round(); return rounded.times(step).toFixed(this.precision); } } // ============ 方案 2: 原生 BigInt 实现 (无需依赖) ============ class BigIntCalculator { constructor(decimals = 2) { this.decimals = decimals; this.multiplier = 10n ** BigInt(decimals); } // 字符串转 BigInt (放大) parse(str) { const [intPart, decPart = ''] = String(str).split('.'); const padded = decPart.padEnd(this.decimals, '0').slice(0, this.decimals); return BigInt(intPart + padded); } // BigInt 转字符串 (缩小) format(value) { const str = value.toString().padStart(this.decimals + 1, '0'); const intPart = str.slice(0, -this.decimals) || '0'; const decPart = str.slice(-this.decimals); return `${intPart}.${decPart}`; } add(a, b) { return this.format(this.parse(a) + this.parse(b)); } subtract(a, b) { return this.format(this.parse(a) - this.parse(b)); } multiply(a, b) { // 乘法后需要除以精度因子 const result = (this.parse(a) * this.parse(b)) / this.multiplier; return this.format(result); } divide(a, b) { // 除法前需要乘以精度因子 const result = (this.parse(a) * this.multiplier) / this.parse(b); return this.format(result); } } // ============ 方案 3: 0.04 步长特殊处理 ============ function roundToStep(value, step = 0.04) { // 处理 0.04 为单位的舍入 const inverse = 1 / step; // 25 return Math.round(value * inverse) / inverse; } // ============ 使用示例 ============ console.log('=== 0.04f 精度处理演示 ===\n'); // 1. Decimal.js 方案 console.log('--- Decimal.js 方案 ---'); const calc = new PrecisionCalculator(2); console.log('加法: 0.1 + 0.2 =', calc.add(0.1, 0.2)); // 0.30 console.log('乘法: 0.1 * 0.2 =', calc.multiply(0.1, 0.2)); // 0.02 console.log('0.04 步长舍入:'); console.log(' 0.05 ->', calc.roundTo004(0.05)); // 0.04 console.log(' 0.06 ->', calc.roundTo004(0.06)); // 0.04 或 0.08 console.log(' 0.10 ->', calc.roundTo004(0.10)); // 0.08 // 2. BigInt 方案 console.log('\n--- BigInt 方案 ---'); const bigCalc = new BigIntCalculator(2); console.log('加法: 0.1 + 0.2 =', bigCalc.add(0.1, 0.2)); console.log('减法: 1.0 - 0.9 =', bigCalc.subtract(1.0, 0.9)); // 3. 步长舍入 console.log('\n--- 0.04 步长舍入 ---'); const testValues = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10]; testValues.forEach(v => { console.log(`${v.toFixed(2)} -> ${roundToStep(v, 0.04).toFixed(2)}`); }); // 4. 货币计算示例 console.log('\n--- 货币计算示例 ---'); const price = new Decimal('19.99'); const quantity = new Decimal('3'); const discount = new Decimal('0.04'); // 4% 折扣 const subtotal = price.times(quantity); const discountAmount = subtotal.times(discount); const total = subtotal.minus(discountAmount); console.log(`单价: ${price}`); console.log(`数量: ${quantity}`); console.log(`小计: ${subtotal.toFixed(2)}`); console.log(`折扣 (4%): ${discountAmount.toFixed(2)}`); console.log(`总计: ${total.toFixed(2)}`); // 5. 浮点数问题对比 console.log('\n--- 浮点数精度问题对比 ---'); console.log('原生 JS: 0.1 + 0.2 =', 0.1 + 0.2); // 0.30000000000000004 console.log('Decimal: 0.1 + 0.2 =', new Decimal(0.1).plus(0.2).toString()); // 0.3 console.log('BigInt: 0.1 + 0.2 =', bigCalc.add(0.1, 0.2)); // 0.30安装依赖:
bash
复制
npm install decimal.js关键特性:
表格
| 方案 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
decimal.js | 功能丰富、易用 | 需要依赖 | 复杂财务计算 |
BigInt | 原生支持、性能高 | 代码较繁琐 | 高频计算、无依赖 |
| 步长舍入 | 简单轻量 | 功能有限 | 特定舍入规则 |
0.04f 特殊含义:
在财务系统中,0.04 可能代表4% 费率/税率
或作为最小计价单位(如某些股票的最小变动价位)
f后缀表示 float,但在 JavaScript 中统一使用 Number 或 Decimal
需要针对特定业务场景(如手续费计算、汇率转换)的定制代码吗?