toNumber.js 575 B

1234567891011121314151617181920
  1. var isArray = require('./isArray');
  2. /**
  3. * covert value into number if numeric
  4. */
  5. function toNumber(val){
  6. // numberic values should come first because of -0
  7. if (typeof val === 'number') return val;
  8. // we want all falsy values (besides -0) to return zero to avoid
  9. // headaches
  10. if (!val) return 0;
  11. if (typeof val === 'string') return parseFloat(val);
  12. // arrays are edge cases. `Number([4]) === 4`
  13. if (isArray(val)) return NaN;
  14. return Number(val);
  15. }
  16. module.exports = toNumber;