题目描述:
给定任意的小数,四舍五入保留三位小数
const dis = 30.999999; //任意小数
const arr = (dis+"").split(".");
let res = 0;
if(arr[1].length > 3) { //判断小数位数
if(arr[1].charAt(3)<5){ //不用进位
res = arr[0]+"." + arr[1].substr(0,3);
}
else { //进位
let k=3;
let xiaoshu = arr[1].split(""); //小数部分化成数组
let jinwei = false; //标记9+1=10的情况
while(xiaoshu[k]>5 || jinwei==true){
if(k==0){
arr[0]++; //第一位小数大于5
}
if((Number(xiaoshu[k-1])+1) > 9) {
jinwei=true;
}
else {
jinwei=false;
}
xiaoshu[k-1]= (Number(xiaoshu[k-1])+1)%10;
k--;
}
res = arr[0]+"." +xiaoshu[0]+xiaoshu[1]+xiaoshu[2]; //拼装结果
}
}
else {
res = dis;
}
console.log(res);