UNPKG

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