UNPKG

2 kBJavaScriptView Raw
1// Convert from Fraction to BigNumber
2//
3// In the configuration of math.js one can specify the default number type to
4// be `number`, `BigNumber`, or `Fraction`. Not all functions support `Fraction`
5// or `BigNumber`, and if not supported these input types will be converted to
6// numbers.
7//
8// When `Fraction` is configured, one may want to fallback to `BigNumber`
9// instead of `number`. Also, one may want to be able to mix `Fraction` and
10// `BigNumber` in operations like summing them up. This can be achieved by
11// adding an extra conversion to the list of conversions as demonstrated in
12// this example.
13
14// Load the math.js core (contains only `import` and `config`)
15const core = require('../../core')
16const math = core.create()
17
18// Configure to use fractions by default
19math.config({ number: 'Fraction' })
20
21// Add a conversion from Faction -> BigNumber
22// this conversion:
23// - must be inserted in the conversions list before the conversion Fraction -> number
24// - must be added to the conversions before loading functions into math.js
25math.typed.conversions.unshift({
26 from: 'Fraction',
27 to: 'BigNumber',
28 convert: function (fraction) {
29 return new math.type.BigNumber(fraction.n).div(fraction.d)
30 }
31})
32
33// Import all data types, functions, constants, the expression parser, etc.
34math.import(require('../../lib'))
35
36// Operators `add` and `divide` do have support for Fractions, so the result
37// will simply be a Fraction (default behavior of math.js).
38const ans1 = math.eval('1/3 + 1/4')
39console.log(math.typeof(ans1), math.format(ans1))
40// outputs "Fraction 7/12"
41
42// Function sqrt doesn't have Fraction support, will now fall back to BigNumber
43// instead of number.
44const ans2 = math.eval('sqrt(4)')
45console.log(math.typeof(ans2), math.format(ans2))
46// outputs "BigNumber 2"
47
48// We can now do operations with mixed Fractions and BigNumbers
49const ans3 = math.add(math.fraction(2, 5), math.bignumber(3))
50console.log(math.typeof(ans3), math.format(ans3))
51// outputs "BigNumber 3.4"