小数点后两位的输入或显示以及四舍五入
1.只可输入小数点后两位
<input type="text" v-model.trim="iptValue" placeholder="自定义金额" @input="handleInput" >
const handleInput = () => {
state.iptValue = state.iptValue.match(/\d*\.{0,1}\d{0,2}/)[0] || null;
};
2.只显示小数点后两位(toFixed()
)五舍六入
1.toFixed() 方法可把指定的数值四舍五入为指定小数位数的数字。
let num = 10.556
console.log(num.toFixed(2)) // 10.56
2.上面的结果看似是正确的,实际上在值为 xx.555的情况就不是我们想要的 四舍五入 的效果,如下:
let num = 10.555
console.log(num.toFixed(2)) // 10.55
3.四舍五入 自定义toFixed()方法
下面使用 Math.round
方法来封装一个 四舍五入 方法。
Math.round()
: 函数返回一个数字, 四舍五入后
最接近的 整数
。
思路 :因为 Math.round()
方法只能返回一个整数
,例如传入的值为 10.555
,将传入的值【 乘以100倍】
就是 1055.5
,用 Math.round()
方法将 1055.5 四舍五入
后返回值 1056
,再将 1056 【除以100倍】
就得到了 10.56
即可。
/**
* multiple:倍数,默认值100,比如10.555 想四舍五入并且保留2位小数,
* 就要乘以100倍后1055.6用 Math.round四舍五入后除以100倍就是四舍五入后的值
*/
let toFixed = (num, multiple = 100) => {
let formattedVal = parseFloat(num);
if (isNaN(formattedVal)){ // 值为NaN
return false
}
formattedVal = Math.round(formattedVal * multiple) / multiple
return formattedVal
}
// 使用方法
console.log(toFixed(10.555)) // 10.56
这个方法不会 补0,例如:
console.log(toFixed(10.000)) // 10
而不是 10.00, 如何补0 如下:
/**
* multiple:倍数,默认值100,比如10.555 想四舍五入并且保留2位小数,
* 就要乘以100倍后1055.6用 Math.round四舍五入后除以100倍就是四舍五入后的值
*/
let toFixed = (num, multiple = 100) => {
let formattedVal = parseFloat(num);
if (isNaN(formattedVal)) { // 值为NaN
return false
}
formattedVal = Math.round(formattedVal * multiple) / multiple
let numToString = formattedVal.toString()
let pos_decimal = numToString.indexOf('.')
if (pos_decimal < 0) {
pos_decimal = numToString.length
numToString += '.'
}
while (numToString.length <= pos_decimal + 2) {
numToString += '0'
}
return numToString
}
// // 使用方法
console.log(toFixed(10)) // 10.00
4.自定义toFixed()高级版
1.补0版本
let newToFixed = (num,d) => { //
return (Math.round(num * Math.pow(10,d)) / Math.pow(10,d)).toFixed(d)
}
console.log(newToFixed(49.999,2)) // 50.00
2.不补0版本
let newToFixed = (num,d) => { // 不补0版本
return Number((Math.round(num * Math.pow(10,d)) / Math.pow(10,d)).toFixed(d))
}
console.log(newToFixed(49.999,2)) // 50
5.向下取整保留两位小数
const numFormat = (num = 0) => {
let quantity = Number(num);
if (quantity > 100000000) {
quantity = Math.floor(quantity * 1000) / 1000 / 100000000;
let floor = quantity.toString();
return floor.substring(0, floor.indexOf(".") + 3) + "亿";
} else if (quantity > 10000) {
quantity = Math.floor(quantity * 1000) / 1000 / 10000;
let floor = quantity.toString();
return floor.substring(0, floor.indexOf(".") + 3) + "万";
} else {
return quantity;
}
};