toNumber.js 1.6 KB

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