一个简单的问题:
0.1 + 0.2 = 0.3
不管是在JavaScript里,还是在其他语言里面,都会出现
0.30000000000000004
尝试过网上很多种方案了,没有一个效果好的。
后来的后来,我发现其实有很好的第三方库已经解决好这个问题,直接拿过来用就好了
尽量不要自己折腾,老老实实用三方库比较好
一.decimal.js
An arbitrary-precision Decimal type for JavaScript.
1.安装
npm install decimal.js
2. 基础使用
加
const Decimal = require('decimal.js')
let x = new Decimal(0.1)
let y =new Decimal(0.2)
console.log(x.plus(y))
输出结果
0.3
减
const Decimal = require('decimal.js')
let x = new Decimal(0.3)
console.log(x.minus(0.1))
console.log(typeof x.minus(0.1))
console.log(Number(x.minus(0.1)))
输出结果
0.2
object
0.2
执行结果是一个Decimal对象,不过可以通过Number方法转成number类型
乘法、除法及链式求值
const Decimal = require('decimal.js')
let x = new Decimal(2)
let y = new Decimal(10.1)
let z = new Decimal(100)
console.log(x.dividedBy(y).plus(z).times(9).floor())
输出结果
901
3. 精确到小数点后几位
先看看JavaScript原有的 toFixed
方法效果吧
console.log(0.123 * 0.323); // 0.039729
console.log((0.123 * 0.323).toFixed(2)); // '0.04'
可以看到 ` toFixed` 方法进行了简单的四舍五入,
然后,toFixed并不会完全的按照四舍五入的原则进行计算,比如下面的
console.log(1.335.toFixed(2)); // '1.33'
所以,如果有非常精确的要求的时候,千万不要直接使用
使用Decimal的`toFixed` 方法则会相对准确的进行四舍五入
const Decimal = require('decimal.js')
let x = new Decimal(0.335)
console.log(x.toFixed(2)); // 0.34
但是有时候,我们不想进行四舍五入怎么办呢?
let x = new Decimal(0.335)
console.log(x.toFixed(2, Decimal.ROUND_DOWN)); // 0.33
暂无评论