中山网站设计收费标准,网站做电子公章违法吗,企业解决方案工作组,网站制作价格表模板前言#xff1a;
针对于小数精度问题#xff0c;本次我们主要推荐两种方式#xff0c;一种是简单的函数封装#xff0c;一种是使用第三方库big.js。
方法一#xff1a;
自封装函数搭配parseFloat和toFixed解决小数精度问题#xff0c;仅适用于解决一般性小数精度问题
针对于小数精度问题本次我们主要推荐两种方式一种是简单的函数封装一种是使用第三方库big.js。
方法一
自封装函数搭配parseFloat和toFixed解决小数精度问题仅适用于解决一般性小数精度问题适用于项目中小数问题比较少的项目。 /*** description: 处理小数精度* param {*} value 需要格式化的数字* param {*} fixedNum 保留的小数位数默认为2* param {*} multiple 乘数默认为1* return {*} */export const handleDecimalPrecision (value, fixedNum 2, multiple 1) {return parseFloat((value * multiple).toFixed(fixedNum))}测试用例
传倍数multiple 是为了展示成百分比比如30%
0.1 0.2 //0.30000000000000004
handleDecimalPrecision(0.1 0.2) //0.3handleDecimalPrecision(0.1 0.2,1,100) //30 传倍数multiple 是为了展示成百分比比如30%
方法二
使用第三方库big.js 。适用于精度问题比较多的项目长期性解决精度问题。以下我们将展示一些常见的使用范围的场景其他的深冷需求可移步至官方文档查看。
big.js特点
简单的API比Java的BigDecimal更快、更小、更易于使用复制JavaScript数字的toExponential、toFixed和toPrecision方法可以访问的十进制浮点格式存储值全面的文档和测试集没有依赖关系相对独立仅使用ECMAScript 3无兼容性问题
安装big.js
npm install big.js -S
引入big.js
script
import Big from big.js
/script
示例以vue为例
code:
templatediv classapp-containerdiv小数精度/divdiv未处理 : 0.1 0.2 {{sum_orgin}}/divdivbigjs处理 : 0.1 0.2 {{sum_bigjs}}/div/div
/templatescript setup
import Big from big.jsconst num1 0.1
const num2 0.2
const sum_orgin num1.value num2.value
const sum_bigjs Big(num1.value).plus(Big(num2.value))
/script
效果图 创建Big number数据
const num1 Big(0.1)
或者
const num2 new Big(0.2)加法精度问题处理 - plus
0.1 0.2 //0.30000000000000004
0.7 0.1 //0.7999999999999999
0.2 0.4 //0.6000000000000001Big(0.1).plus(Big(0.2)) //0.3
Big(0.1).plus(Big(0.24)) //0.34
减法精度问题 - minus
0.3 - 0.2 //0.09999999999999998
1.5 - 1.2 //0.30000000000000004Big(0.3).minus(Big(0.2)) //0.1
乘法精度问题 - times
19.9 * 100 //1989.9999999999998
0.8 * 3 //2.4000000000000004
35.41 * 100 //3540.9999999999995Big(19.9).times(Big(100)) //1990
除法精度问题 - div
0.3 / 0.1 //2.9999999999999996
0.69 / 10 //0.06899999999999999
Big(0.3).div(Big(0.1)) //3
保留小数位数(四舍五入) - round
1 / 3 //0.3333333333333333
Big(1).div(Big(3)).round(3) //0.333big.js运算符说明 运算符 说明 abs 取绝对值 cmp compare的缩写即比较函数 div 除法 eq equal的缩写即相等比较 gt 大于 gte 小于等于e表示equal lt 小于 lte 小于等于e表示equal minus 减法 mod 取余 plus 加法 pow 次方 prec 按精度舍入参数表示整体位数 round 按精度舍入参数表示小数点后位数 sqrt 开方 times 乘法 toExponential 转化为科学计数法参数代表精度位数 toFied 补全位数参数代表小数点后位数 toJSON/toString 转化为字符串 toPrecision 按指定有效位数展示参数为有效位数 toNumber 转化为JavaScript中number类型 valueOf 包含负号如果为负数或者-0的字符串
bigjs官网文档