UNPKG

2.17 kBJavaScriptView Raw
1'use strict';
2
3var deepMap = require('./../utils/collection/deepMap');
4
5function factory(type, config, load, typed) {
6 /**
7 * Create a number or convert a string, boolean, or unit to a number.
8 * When value is a matrix, all elements will be converted to number.
9 *
10 * Syntax:
11 *
12 * math.number(value)
13 * math.number(unit, valuelessUnit)
14 *
15 * Examples:
16 *
17 * math.number(2) // returns number 2
18 * math.number('7.2') // returns number 7.2
19 * math.number(true) // returns number 1
20 * math.number([true, false, true, true]) // returns [1, 0, 1, 1]
21 * math.number(math.unit('52cm'), 'm') // returns 0.52
22 *
23 * See also:
24 *
25 * bignumber, boolean, complex, index, matrix, string, unit
26 *
27 * @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted
28 * @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number
29 * @return {number | Array | Matrix} The created number
30 */
31 var number = typed('number', {
32 '': function _() {
33 return 0;
34 },
35
36 'number': function number(x) {
37 return x;
38 },
39
40 'string': function string(x) {
41 var num = Number(x);
42 if (isNaN(num)) {
43 throw new SyntaxError('String "' + x + '" is no valid number');
44 }
45 return num;
46 },
47
48 'BigNumber': function BigNumber(x) {
49 return x.toNumber();
50 },
51
52 'Fraction': function Fraction(x) {
53 return x.valueOf();
54 },
55
56 'Unit': function Unit(x) {
57 throw new Error('Second argument with valueless unit expected');
58 },
59
60 'null': function _null(x) {
61 return 0;
62 },
63
64 'Unit, string | Unit': function UnitStringUnit(unit, valuelessUnit) {
65 return unit.toNumber(valuelessUnit);
66 },
67
68 'Array | Matrix': function ArrayMatrix(x) {
69 return deepMap(x, number);
70 }
71 });
72
73 number.toTex = {
74 0: '0',
75 1: '\\left(${args[0]}\\right)',
76 2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)'
77 };
78
79 return number;
80}
81
82exports.name = 'number';
83exports.factory = factory;
\No newline at end of file