Javascript精确小数四舍五入
解决了 Math.round(number * 100) / 100 中对如9.995处理结果错误的问题。
需要注意的是,输入的值仍然是有限制的。当小数位数过多,如9.9449999999999999,此时仍会因超出JavaScript能表示的小数范围而出错(该数处理结果为9.95而非9.94,因为超出的原因数值被自动变更为了9.945)。
function getRounding(number, digit) {
if ( typeof digit === 'undefined') digit = 2;
//console.log(digit)
let num = Math.pow(10, digit);
//console.log("num: " + num)
let multipledNum = num * number;
//console.log("multipledNum: " + multipledNum)
let flooredNum = Math.floor(multipledNum);
//console.log("flooredNum:" + flooredNum)
let numberStr = number.toString();
//console.log("numberStr:" + numberStr)
let indicatorIndex = numberStr.indexOf('.');
//console.log("indicatorIndex: " + indicatorIndex)
if (indicatorIndex > -1) {
let indicator = parseInt(numberStr.slice(indicatorIndex + digit + 1, indicatorIndex + digit + 2));
//console.log("indicator: " + indicator)
if (isNaN(indicator)) {
//console.log("no indicator")
return number
}
if (indicator < 5) return flooredNum / num;
return (flooredNum + 1) / num;
}
else {
//console.log("number: " + number)
return number;
}
}