UNPKG

2.26 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// Create an empty math.js instance, with only typed
15// (every instance contains `import` and `config` also out of the box)
16const { create, typedDependencies, all } = require('../..')
17const math = create({
18 typedDependencies
19})
20
21// TODO: this should be much easier
22const allExceptLoaded = Object.keys(all)
23 .map(key => all[key])
24 .filter(factory => math[factory.fn] === undefined)
25
26// Configure to use fractions by default
27math.config({ number: 'Fraction' })
28
29// Add a conversion from Faction -> BigNumber
30// this conversion:
31// - must be inserted in the conversions list before the conversion Fraction -> number
32// - must be added to the conversions before loading functions into math.js
33math.typed.conversions.unshift({
34 from: 'Fraction',
35 to: 'BigNumber',
36 convert: function (fraction) {
37 return new math.BigNumber(fraction.n).div(fraction.d)
38 }
39})
40
41// Import all data types, functions, constants, the expression parser, etc.
42math.import(allExceptLoaded)
43
44// Operators `add` and `divide` do have support for Fractions, so the result
45// will simply be a Fraction (default behavior of math.js).
46const ans1 = math.evaluate('1/3 + 1/4')
47console.log(math.typeOf(ans1), math.format(ans1))
48// outputs "Fraction 7/12"
49
50// Function sqrt doesn't have Fraction support, will now fall back to BigNumber
51// instead of number.
52const ans2 = math.evaluate('sqrt(4)')
53console.log(math.typeOf(ans2), math.format(ans2))
54// outputs "BigNumber 2"
55
56// We can now do operations with mixed Fractions and BigNumbers
57const ans3 = math.add(math.fraction(2, 5), math.bignumber(3))
58console.log(math.typeOf(ans3), math.format(ans3))
59// outputs "BigNumber 3.4"