toNumber.js 1.5 KB

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