handleMoney(amount, decimalPlaces = 2) {
// 定义货币的最小单位(例如:分)
const DECIMAL_PLACES_MULTIPLIER = Math.pow(10, decimalPlaces);
// 转换为整数,以最小货币单位进行计算
let integerAmount = Math.round(amount * DECIMAL_PLACES_MULTIPLIER);
// 进行计算... 在这里可以添加你的计算逻辑
// 例如:integerAmount += someOtherIntegerAmount;
// 将整数结果转换回带有指定小数位数的字符串
// 不使用toFixed(),因为它会四舍五入
let resultString = (integerAmount / DECIMAL_PLACES_MULTIPLIER).toString();
let decimalPart = resultString.split('.')[1];
// 如果小数部分不足指定的小数位数,用0填充
if (decimalPart && decimalPart.length < decimalPlaces) {
resultString += '0'.repeat(decimalPlaces - decimalPart.length);
}
// 如果小数部分存在且超过指定的小数位数,则截断
if (decimalPart && decimalPart.length > decimalPlaces) {
resultString = resultString.split('.')[0] + '.' + decimalPart.substring(0, decimalPlaces);
}
// 如果结果为整数,则移除小数点
if (decimalPlaces === 0 && resultString.includes('.')) {
resultString = resultString.split('.')[0];
}
return resultString;
},
js 解决前端精度问题
于 2024-04-26 16:14:26 首次发布