js四捨五入很自然想到 toFixed 方法
然而toFixed方法存在問題
console.log(0.995.toFixed(2)) //0.99 ****出實際應該爲1.00
console.log(1.995.toFixed(2)) //2.00
現在提供一個方法
function toDecimal(x) {
var num = Math.round(x*100)/100;//此處x在做乘法是會進行隱士類型轉換數值型,如果轉換失敗最終num=NaN
if (isNaN(num)) {
return false;
}
var str = num.toString();
var rs = str.indexOf('.');
if (rs < 0) {
str += '.';
}
while (str.length <= 3) {
str += '0';
}
return str;
}
console.log(toDecimal(0.995))//1.00