项目中使用了计算之后四舍五入
例子:数量 * 单价 = 总价
5 * 2.093 = 10.465 使用toFixed四舍五入保留两位小数却是 10.46
1、使用 Math.toFixed() 函数
1)方法介绍
toFixed() 方法可以将数字转换为字符串,并指定小数点后保留几位。如果小数实际位数不够指定的位数,不足的部分会补 0。所有主要浏览器都支持 toFixed() 方法。
toFixed() 使用的是银行家舍入规则:四舍六入五取偶(又称四舍六入五留双)
2)银行家舍入法:
四舍六入五考虑,五后非零就进一,五后为零看奇偶,五前为偶应舍去,五前为奇要进一
使用toFixed()函数,有可能会出现精度问题,可以考虑到用Math.round()函数‘
自定义函数 customToFixed (解决小数点最后一位为5的情况)
export function customToFixed(x, n) {
let f_x = parseFloat(x)
if (isNaN(f_x)) {
console.warn('传递参数不是数字!')
return false
}
f_x = Math.round(x * Math.pow(10, n)) / Math.pow(10, n)
let s_x = f_x.toString()
let pos_decimal = s_x.indexOf('.')
if (pos_decimal < 0) {
pos_decimal = s_x.length
s_x += '.'
}
while (s_x.length <= pos_decimal + n) {
s_x += '0'
}
return s_x
}