UNPKG

1.75 kBJavaScriptView Raw
1/* eslint-disable no-loss-of-precision */
2
3// BigNumbers
4
5const { create, all } = require('..')
6
7// configure the default type of numbers as BigNumbers
8const config = {
9 // Default type of number
10 // Available options: 'number' (default), 'BigNumber', or 'Fraction'
11 number: 'BigNumber',
12
13 // Number of significant digits for BigNumbers
14 precision: 20
15}
16const math = create(all, config)
17
18console.log('round-off errors with numbers')
19print(math.add(0.1, 0.2)) // number, 0.30000000000000004
20print(math.divide(0.3, 0.2)) // number, 1.4999999999999998
21console.log()
22
23console.log('no round-off errors with BigNumbers')
24print(math.add(math.bignumber(0.1), math.bignumber(0.2))) // BigNumber, 0.3
25print(math.divide(math.bignumber(0.3), math.bignumber(0.2))) // BigNumber, 1.5
26console.log()
27
28console.log('create BigNumbers from strings when exceeding the range of a number')
29print(math.bignumber(1.2e+500)) // BigNumber, Infinity WRONG
30print(math.bignumber('1.2e+500')) // BigNumber, 1.2e+500
31console.log()
32
33console.log('BigNumbers still have a limited precision and are no silve bullet')
34const third = math.divide(math.bignumber(1), math.bignumber(3))
35const total = math.add(third, third, third)
36print(total) // BigNumber, 0.99999999999999999999
37console.log()
38
39// one can work conveniently with BigNumbers using the expression parser.
40// note though that BigNumbers are only supported in arithmetic functions
41console.log('use BigNumbers in the expression parser')
42print(math.evaluate('0.1 + 0.2')) // BigNumber, 0.3
43print(math.evaluate('0.3 / 0.2')) // BigNumber, 1.5
44console.log()
45
46/**
47 * Helper function to output a value in the console. Value will be formatted.
48 * @param {*} value
49 */
50function print (value) {
51 console.log(math.format(value))
52}