<!--script src="https://raw.githubusercontent.com/iriscouch/bigdecimal.js/v0.6.1/lib/bigdecimal.js"></script-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/9.0.1/bignumber.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/big.js/6.0.3/big.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.2.1/decimal.min.js"></script>
<!--script src="https://raw.githubusercontent.com/infusion/Fraction.js/v4.0.12/fraction.min.js"></script-->
var a = 0.1;
var b = 0.2;
((a + b) * b);
var a = 0.1;
var b = 0.2;
((a + b) * b);
var a = new Decimal("0.1");
var b = new Decimal("0.2");
a.plus(b).times(b);
var a = new Big("0.1");
var b = new Big("0.2");
a.plus(b).mul(b);
var a = new BigNumber("0.1");
var b = new BigNumber("0.2");
a.plus(b).multipliedBy(b);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native | |
Native + toFixed | |
decimal.js | |
big.js | |
bignumber.js |
Test name | Executions per second |
---|---|
Native | 946886400.0 Ops/sec |
Native + toFixed | 940900992.0 Ops/sec |
decimal.js | 678699.4 Ops/sec |
big.js | 1002983.4 Ops/sec |
bignumber.js | 563807.6 Ops/sec |
Let's break down what's being tested in this benchmark.
Overview
The benchmark is comparing the performance of four different approaches to perform a simple mathematical calculation: (a + b) * b
, where a
and b
are decimal numbers.
Libraries involved
Three libraries are being compared:
These libraries aim to provide more precise and flexible ways of handling decimal numbers compared to the built-in JavaScript Number type.
Test cases
Five test cases are being executed:
Number
type..toFixed()
method call to ensure that the result is a string representation of the decimal number (to avoid potential precision issues).Decimal
class.Big
class.BigNumber
class.Pros and Cons
Here are some general pros and cons of each approach:
Alternative approaches
If you're looking for alternative ways to perform decimal arithmetic in JavaScript:
Number
type may lead to precision issues, especially when dealing with complex calculations or large decimal numbers.I hope this explanation helps!