自学内容网 自学内容网

前端开发使用Big.js精算避免误差

1、下载

npm install big.js

全局引入还是局部引入可根据项目框架及个人需求

2、静态引入

< script  src =' https://unpkg.com/big.js@6.0.0/big.mjs ' > </ script >

或者

import Big from 'https://raw.githubusercontent.com/mikemcl/big.js/v6.0.0/big.mjs';
import Big from 'https://unpkg.com/big.js@6.0.0/big.mjs';

3、常用方法

加法plus

0.1 + 0.2     // 0.30000000000000004
x = Big(0.1)
y = x.plus(0.2)   // '0.3'
Big(0.7).plus(x).plus(y)   // '1.1'

减法minus

0.3 - 0.1 // 0.19999999999999998
x = Big(0.3)
x.minus(0.1) // "0.2"
x // “0.3"

 乘法times

0.6 * 3 // 1.7999999999999998
x = Big(0.6)
y = x.times(3) // '1.8'

除法div

x = Big(2);
y = Big(3);
z = x.div(y) // "0.6666666667"

保留两位小数toFixed

Big(12).toFixed(2) // 12.00

开发中有遇到过想要数字不四舍五入不进位的数字需要处理如12.566想要取12.56舍弃其它不转字符串切割暂时没有想法,有想法可以互相讨论谢谢。


原文地址:https://blog.csdn.net/m0_65360496/article/details/140662618

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!