方法一 (不會四舍五入)
此方法不會進(jìn)行四舍五入,而是直接截取,不足則補0,默認(rèn)保留2位
val 為需要格式化的數(shù)值
dotIdx 為截取的位數(shù)
如:
const getFloatCut = (val, dotIdx=2) => {
var re = new RegExp("([0-9]+\\.[0-9]{" + dotIdx + "})[0-9]*")
var aNew = val.toString().replace(re, "$1");
return parseFloat(aNew).toFixed(dotIdx)
}
getFloatCut(3,2) //3.00
getFloatCut(3.999,2) //3.99
方法二(會四舍五入)
此方法會進(jìn)行四舍五入,不足則補0,默認(rèn)保留2位
val 為需要格式化的數(shù)值
dotIdx 為截取的位數(shù)
如:
const getFloatCut = (val, dotIdx=2) => {
var aNew = Math.round(val * Math.pow(10, dotIdx))
aNew = aNew / Math.pow(10, dotIdx)
return parseFloat(aNew).toFixed(dotIdx)
}
getFloatCut(3,2) //3.00
getFloatCut(3.999,2) //4.00
合并上述方法:
const getFloatCut = (val, dotIdx = 2, cutFlag = false) => {
if (cutFlag) {
// 不要四舍五入,直接截取
// getFloatCut(3.99999,2,true) => 3.99
var re = new RegExp("([0-9]+\\.[0-9]{" + dotIdx + "})[0-9]*")
var aNew = val.toString().replace(re, "$1");
return parseFloat(aNew).toFixed(dotIdx)
} else {
// 要四舍五入
// getFloatCut(3.99999,2) => 4.00
var aNew = Math.round(val * Math.pow(10, dotIdx))
aNew = aNew / Math.pow(10, dotIdx)
return parseFloat(aNew).toFixed(dotIdx)
}
}
getFloatCut(3.99999,2,true)//3.99
getFloatCut(3.99999,2)//4.00