对toFixed计算失去精度的一点优化

在项目中保留2位小数通常使用toFixed(2),但有时使用它会存在四舍五入方面的错误,比如:

1.335.toFixed(2) 变成1.33
69.945.toFixed(2)变成69.94

查询资料时突然想到当小数后为5时toFixed不适用,是否可自动帮它进一位再计算。下面是一些实现:

function getRound(num,s){
				let index = num.toString().indexOf('.');
				//console.log('位置:',index);
				if(index>0){
					let last = num.toString().length-1-index;
					//console.log('last:',last);
					if(last>=s){
						let arr = num.toString().split('');
						if(arr[index+s+1]==5){
							//console.log('变动1',num);
							num=num+(5/Math.pow(10,index+s+1)*(num>0?1:-1));
							//console.log('变动2',num);
							num = Math.round(num*Math.pow(10,s))/Math.pow(10,s);
						}else{
							num = Math.round(num*Math.pow(10,s))/Math.pow(10,s);
						}
						let index2 = num.toString().indexOf('.');
						if(index2<0){//考虑结果刚好为整数的情况如100,500
							num+='.';
							for(let i=0;i<s;i++){
								num+='0';
							}
						}else{//考虑结果小数点少几位的情况,如0.1
							let last = num.toString().length-1-index2;
							if(last<s){
								for(let i=0;i<(s-last);i++){
									num+='0';
								}
							}
						}
					}else{
						for(let i=0;i<(s-last);i++){
							num+='0';
						}
					}
				}else{
					num+='.';
					for(let i=0;i<s;i++){
						num+='0';
					}
				}
				console.log('num:',num);
			}
			getRound(240.025,2);
			getRound(240.005,2);
			getRound(240.995,2);
			getRound(249.905,2);
			getRound(249.995,2);
			getRound(99.995,2); 
			getRound(0.995,2); 
			getRound(0.95,2); 
			getRound(0.005,2); 
			getRound(0.095,2); 

结果:

num: 240.03 
num: 240.01
num: 241.00
num: 249.91
num: 250.00
num: 100.00
num: 1.00
num: 0.95
num: 0.01
num: 0.10

从效果来看,还是比较符合预期…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值