code_junkie

Is there a (built-in) way in JavaScript to check if a string is a valid number?

Nov 11th, 2011
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. isNaN(num) // returns true if the variable does NOT contain a valid number
  2.  
  3. isNaN(123) // false
  4. isNaN('123') // false
  5. isNaN('foo') // true
  6. isNaN('10px') // true
  7.  
  8. function isNumeric(num){
  9. return !isNaN(num)
  10. }
  11.  
  12. +num // returns the numeric value of the string, or NaN if the
  13. // string isn't purely numeric characters
  14.  
  15. +'12' // 12
  16. +'foo' // NaN
  17. +'12px' // NaN
  18.  
  19. parseInt(num) // extracts a numeric value from the
  20. // start of the string, or NaN.
  21.  
  22. parseInt('12') // 12
  23. parseInt('aaa') // NaN
  24. parseInt('12px') // 12
  25. parseInt('foo2') // NaN These last two may be different
  26. parseInt('12a5') // 12 from what you expected to see.
  27.  
  28. parseInt(12.345) // 12
  29. parseInt('12.345') // 12
  30. +'12.345' // 12.345
  31.  
  32. +'' // 0
  33. isNaN('') // false
  34.  
  35. parseInt('') // NaN
  36.  
  37. var num = "987238";
  38.  
  39. if(num.match(/^d+$/)){
  40. //valid integer
  41. }else if(num.match(/^d+.d+$/)){
  42. //valid float
  43. }else{
  44. //not valid number
  45. }
Add Comment
Please, Sign In to add comment