js 解决前端精度问题

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;
			},

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值