这里是重写了Number的toFixed,也可以自己抽取成一个方法
/**
* @description:保留两位小数,可直接截取,可四舍五入 重置Number 的 toFixed()方法
* @param {Number} decimals 小数位数,默认2,最多10
* @return {Boolean} isAddZero 不够小数位是否添0 默认不添加
* @return {Boolean} isRounding 是否四舍五入,默认是
* @example 123.10293.toFixed(2,true) => 123.10
* @Author: liuxin
*/
Number.prototype.toFixed = function (decimals = 2, isAddZero = false, isRounding = true) {
const preNum = this;
if (isNaN(preNum) || (!preNum && preNum !== 0)) {
return ''
}
// 最多10位小数
if (decimals > 10) {
decimals = 10;
}
// 先进行四舍五入
let num = 0;
if (isRounding === true) {
const decimalsNumTemp = Math.pow(10, decimals); // 取保留的小数最大整数值 如10 100 1000等
num = Math.round(parseFloat(preNum) * decimalsNumTemp) / decimalsNumTemp;
}
// 默认为保留的小数点后两位
let tempNum = Number(num)
let pointIndex = String(tempNum).indexOf('.') + 1 // 获取小数点的位置 + 1
let pointCount = pointIndex ? String(tempNum).length - pointIndex + 1 : 0 // 获取小数点后的个数(需要保证有小数位)
// 小数位小于需要截取的位数
if (pointIndex === 0 || pointCount <= decimals) {
// 源数据为整数或者小数点后面小于decimals位的作补零处理
if (isAddZero === true) {
let tempNumA = tempNum
if (pointIndex === 0) {
tempNumA = `${tempNumA}.`
for (let index = 0; index < decimals - pointCount; index++) {
tempNumA = `${tempNumA}0`
}
} else {
for (let index = 0; index < decimals - pointCount; index++) {
tempNumA = `${tempNumA}0`
}
}
return tempNumA;
}
return tempNum
}
let realVal = '';
// 截取当前数据到小数点后decimals位
realVal = `${String(tempNum).split('.')[0]}.${String(tempNum)
.split('.')[1]
.substring(0, decimals)}`
// 判断截取之后数据的数值是否为0
if (realVal == 0) {
realVal = 0
}
return realVal
}
// 测试代码:
console.log("1.123421.toFixed() ===> " + (1.123421).toFixed());
console.log("1.2666.toFixed() ===> " + (1.2666).toFixed());
console.log("1.356.toFixed() ===> " + (1.356).toFixed());
console.log("1.099.toFixed() ===> " + (1.09).toFixed());