| 1 |
var baseTrim = require('./_baseTrim'), |
| 2 |
isObject = require('./isObject'), |
| 3 |
isSymbol = require('./isSymbol'); |
| 4 |
|
| 5 |
/** Used as references for various `Number` constants. */ |
| 6 |
var NAN = 0 / 0; |
| 7 |
|
| 8 |
/** Used to detect bad signed hexadecimal string values. */ |
| 9 |
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; |
| 10 |
|
| 11 |
/** Used to detect binary string values. */ |
| 12 |
var reIsBinary = /^0b[01]+$/i; |
| 13 |
|
| 14 |
/** Used to detect octal string values. */ |
| 15 |
var reIsOctal = /^0o[0-7]+$/i; |
| 16 |
|
| 17 |
/** Built-in method references without a dependency on `root`. */ |
| 18 |
var freeParseInt = parseInt; |
| 19 |
|
| 20 |
/** |
| 21 |
* Converts `value` to a number. |
| 22 |
* |
| 23 |
* @static |
| 24 |
* @memberOf _ |
| 25 |
* @since 4.0.0 |
| 26 |
* @category Lang |
| 27 |
* @param {*} value The value to process. |
| 28 |
* @returns {number} Returns the number. |
| 29 |
* @example |
| 30 |
* |
| 31 |
* _.toNumber(3.2); |
| 32 |
* // => 3.2 |
| 33 |
* |
| 34 |
* _.toNumber(Number.MIN_VALUE); |
| 35 |
* // => 5e-324 |
| 36 |
* |
| 37 |
* _.toNumber(Infinity); |
| 38 |
* // => Infinity |
| 39 |
* |
| 40 |
* _.toNumber('3.2'); |
| 41 |
* // => 3.2 |
| 42 |
*/ |
| 43 |
function toNumber(value) { |
| 44 |
if (typeof value == 'number') { |
| 45 |
return value; |
| 46 |
} |
| 47 |
if (isSymbol(value)) { |
| 48 |
return NAN; |
| 49 |
} |
| 50 |
if (isObject(value)) { |
| 51 |
var other = typeof value.valueOf == 'function' ? value.valueOf() : value; |
| 52 |
value = isObject(other) ? (other + '') : other; |
| 53 |
} |
| 54 |
if (typeof value != 'string') { |
| 55 |
return value === 0 ? value : +value; |
| 56 |
} |
| 57 |
value = baseTrim(value); |
| 58 |
var isBinary = reIsBinary.test(value); |
| 59 |
return (isBinary || reIsOctal.test(value)) |
| 60 |
? freeParseInt(value.slice(2), isBinary ? 2 : 8) |
| 61 |
: (reIsBadHex.test(value) ? NAN : +value); |
| 62 |
} |
| 63 |
|
| 64 |
module.exports = toNumber; |