UNPKG

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