在处理后端返回的双精度浮点数时,前端可能会遇到精度丢失或显示异常的问题。以下是一些常见的解决方案:
// 后端返回
{
"amount": "123456789012345678.123456789012345678"
}
// 前端处理
const amount = parseFloat(response.amount);
decimal.js
或 big.js
)来处理浮点数运算。// 使用 decimal.js
import Decimal from 'decimal.js';
const amount = new Decimal(response.amount);
const result = amount.plus(new Decimal('0.1'));
const amount = parseFloat(response.amount).toFixed(2); // 保留两位小数
// 后端返回
{
"amount": 12345678901234567812 // 实际值为 123456789012345678.12
}
// 前端处理
const amount = response.amount / 100;
json-bigint
)。import JSONbig from 'json-bigint';
const response = JSONbig.parse('{"amount": 123456789012345678.123456789012345678}');
const amount = response.amount;
BigDecimal
)来处理高精度浮点数。class BigDecimal {
constructor(value) {
this.value = value;
}
// 实现加减乘除等方法
}
const amount = new BigDecimal(response.amount);
根据具体需求和项目复杂度,可以选择不同的解决方案。如果精度要求不高,简单的字符串传输或限制小数位数即可;如果需要进行复杂运算,建议使用高精度库或自定义数据类型。