一直在用toFixed()方法做浮点数的舍入取值,如果只是客户端展示数据是没有多大问题的,但是如果涉及到和后端互交,数据的精度可能会导致接口对接失败,当然了,涉及安全性的数值,比如金额之类的不应该放在前端计算,应该以后端为准,少数情况下如果需要的时候,则需要修复其精度
1.出现问题的场景
- 首先,我们发现在ie浏览器与其他的主流浏览器中,由于二进制下浮点数的存储问题,toFixed()的行为是不一样的,也说明了各浏览器厂家的做法不一致。
在ie11中:
0.015.toFixed(2) // 打印结果:"0.02"
在chrome中:
0.015.toFixed(2) // 打印结果:"0.01"
对于此类问题,部分场景是不可接受的,测试可能会打出一个兼容性的bug
- 其次,我们虽然知道,toFixed()是一种银行家舍入,但是他确是入五取单,而不是银行家舍入所说的入五取双,同样是银行家舍入,此函数计算精度与后台java等语言的银行家舍入精度不同,可能照成接口验证失败。
在前端浏览器中:
0.025.toFixed(2) // 打印结果:"0.03" 0.035.toFixed(2) // 打印结果:"0.03"
在后端服务器中:
0.025.setScale(2,RoundingMode.HALF_EVEN) // 打印结果:"0.02" 0.035.setScale(2,RoundingMode.HALF_EVEN) // 打印结果:"0.04"
事实上,正确的做法应该是:有关金额的运算应该完全交由后端计算,然后交给前端展示
2.修复方案
方案很简单,我们只要重写Number.prototype.toFixed方法就可以了。
- 如果我们需要普通的四舍五入:
/* eslint-disable no-extend-native */ // 规避eslint不可修改原型报错 Number.prototype.originalToFixed = Number.prototype.toFixed // 保留原方法 Number.prototype.toFixed = function(length = 0) { // 默认保留0位小数 let result const thisNum = this * Math.pow(10, length) // 将数据化为整数,方便处理 const thisNumList = thisNum.toString().split('.') // 分离整数与小数 if (thisNumList.length === 1) result = thisNum.toString() // 如果只有整数,则不需要处理 else { if (Number(thisNumList[1][0]) >= 5) result = (Number(thisNumList[0]) + 1).toString() // 五入 else (Number(thisNumList[1][0]) < 5) result = thisNumList[0] // 四舍 } if (length === 0) return result else { while (result.length < length + 1) { // 如果位数不够,则用0补齐 result = '0' + result } return result.slice(0, (result.length - length)) + '.' + result.slice(result.length - length) } }
- 如果我们需要使用正常的银行家舍入:
/* eslint-disable no-extend-native */ // 规避eslint不可修改原型报错 Number.prototype.originalToFixed = Number.prototype.toFixed // 保留原方法 Number.prototype.toFixed = function(length = 0) { // 默认保留0位小数 let result const thisNum = this * Math.pow(10, length) // 将数据化为整数,方便处理 const thisNumList = thisNum.toString().split('.') // 分离整数与小数 if (thisNumList.length === 1) result = thisNum.toString() // 如果只有整数,则不需要处理 else { if (Number(thisNumList[1][0]) > 5) result = (Number(thisNumList[0]) + 1).toString() // 六入 else if (Number(thisNumList[1][0]) < 5) result = thisNumList[0] // 四舍 else { // 判断5的情况 if (thisNumList[1].length > 1) result = (Number(thisNumList[0]) + 1).toString() // 如果5后还有位数则入 else { if (Number(thisNumList[0][thisNumList[0].length - 1]) % 2 === 0) result = thisNumList[0] // 五前为偶应舍去 else result = (Number(thisNumList[0]) + 1).toString() // 五前为奇要进一 } } } if (length === 0) return result else { while (result.length < length + 1) { // 如果位数不够,则用0补齐 result = '0' + result } return result.slice(0, (result.length - length)) + '.' + result.slice(result.length - length) } }
这样就统一了舍入的精度,可以根据后台需要选择。