bignumber.js 解决精度

安装

安装:npm install bignumber.js

使用

使用:const BigNumber = require('bignumber.js');

ES module

import BigNumber from "bignumber.js";

// or maybe

import { BigNumber } from "bignumber.js";

// else

import { BigNumber } from "./node_modules/bignumber.js/bignumber.mjs";

实例

let c = 1-(721 / 1000).toFixed(1)  // 0.30000000000004
let d = new BigNumber(1-(0 / 1000)).toFixed(2)     
// 用 BigNumber 约束精度,但是保留2位小数会返回1.00(字符串),所以还需要转成数字类型
let a = Number(new BigNumber(1-(721 / 1000)).toFixed(1))  // 0.3
let b = Number(new BigNumber(1-(0 / 1000)).toFixed(1)) // 1

加减乘除

​加

const a = 0.1 + 0.2                         // 0.30000000000000004
const x = new BigNumber(0.1);               // 0.1
const y = x.plus(0.2);                      // 0.3
const z = BigNumber(0.7).plus(x).plus(y).toFixed(2);  // 1.10

0.3 - 0.1                                 // 0.19999999999999998
const x = new BigNumber(0.3);
const y = x.minus(0.1)                    // 0.2
const z = BigNumber(0.7).minus(x).minus(y).toFixed(2);  // 0.20

const a = 0.6 * 3                            // 1.7999999999999998
const x = new BigNumber(0.6)                 // 0.6
const y = x.times(3)                         // '1.8'
const z = BigNumber('7e+500').times(y)       // '1.26e+501'

const x = new BigNumber(355)
const y = new BigNumber(113)
x.div(y)                                 // '3.14159292035398230088'
x.div(5)                                 // '71'
 
BigNumber.config({ DECIMAL_PLACES: 2 })
const z = x.div(y)                         // '3.14'

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值