UNPKG

3.12 kBJavaScriptView Raw
1import { factory } from '../utils/factory.js';
2import { deepMap } from '../utils/collection.js';
3var name = 'number';
4var dependencies = ['typed'];
5export var createNumber = /* #__PURE__ */factory(name, dependencies, (_ref) => {
6 var {
7 typed
8 } = _ref;
9
10 /**
11 * Create a number or convert a string, boolean, or unit to a number.
12 * When value is a matrix, all elements will be converted to number.
13 *
14 * Syntax:
15 *
16 * math.number(value)
17 * math.number(unit, valuelessUnit)
18 *
19 * Examples:
20 *
21 * math.number(2) // returns number 2
22 * math.number('7.2') // returns number 7.2
23 * math.number(true) // returns number 1
24 * math.number([true, false, true, true]) // returns [1, 0, 1, 1]
25 * math.number(math.unit('52cm'), 'm') // returns 0.52
26 *
27 * See also:
28 *
29 * bignumber, boolean, complex, index, matrix, string, unit
30 *
31 * @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted
32 * @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number
33 * @return {number | Array | Matrix} The created number
34 */
35 var number = typed('number', {
36 '': function _() {
37 return 0;
38 },
39 number: function number(x) {
40 return x;
41 },
42 string: function string(x) {
43 if (x === 'NaN') return NaN;
44 var size = 0;
45 var boxMatch = x.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);
46
47 if (boxMatch) {
48 // x includes a size suffix like 0xffffi32, so we extract
49 // the suffix and remove it from x
50 size = Number(boxMatch[2]);
51 x = boxMatch[1];
52 }
53
54 var num = Number(x);
55
56 if (isNaN(num)) {
57 throw new SyntaxError('String "' + x + '" is no valid number');
58 }
59
60 if (boxMatch) {
61 // x is a signed bin, oct, or hex literal
62 // num is the value of string x if x is interpreted as unsigned
63 if (num > 2 ** size - 1) {
64 // literal is too large for size suffix
65 throw new SyntaxError("String \"".concat(x, "\" is out of range"));
66 } // check if the bit at index size - 1 is set and if so do the twos complement
67
68
69 if (num >= 2 ** (size - 1)) {
70 num = num - 2 ** size;
71 }
72 }
73
74 return num;
75 },
76 BigNumber: function BigNumber(x) {
77 return x.toNumber();
78 },
79 Fraction: function Fraction(x) {
80 return x.valueOf();
81 },
82 Unit: function Unit(x) {
83 throw new Error('Second argument with valueless unit expected');
84 },
85 null: function _null(x) {
86 return 0;
87 },
88 'Unit, string | Unit': function UnitStringUnit(unit, valuelessUnit) {
89 return unit.toNumber(valuelessUnit);
90 },
91 'Array | Matrix': function ArrayMatrix(x) {
92 return deepMap(x, this);
93 }
94 }); // reviver function to parse a JSON object like:
95 //
96 // {"mathjs":"number","value":"2.3"}
97 //
98 // into a number 2.3
99
100 number.fromJSON = function (json) {
101 return parseFloat(json.value);
102 };
103
104 return number;
105});
\No newline at end of file