在项目中保留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
从效果来看,还是比较符合预期…