You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.5 KiB

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