0
点赞
收藏
分享

微信扫一扫

前端JavaScript处理小数精度问题(最佳实践)

前言:

针对于小数精度问题,本次我们主要推荐两种方式,一种是简单的函数封装,一种是使用第三方库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.3
 
handleDecimalPrecision(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:

<template>
  <div class="app-container">
    <div>小数精度</div>
    <div>未处理 : 0.1 + 0.2 = {{sum_orgin}}</div>
    <div>bigjs处理 : 0.1 + 0.2 = {{sum_bigjs}}</div>
  </div>
</template>
 
<script setup>
import Big from 'big.js'
 
const 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.6000000000000001
 
Big(0.1).plus(Big(0.2)) //0.3
Big(0.1).plus(Big(0.24)) //0.34

举报

相关推荐

0 条评论