UNPKG

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