0

I want a concise expression to tell me if a given value is an integer or float. When provided the input value NaN or Infinity, I want the output value to be false, so this rules out simply checking whether typeof(val) == 'number'

Desired input / output:

  • 1 => true
  • -42 => true
  • 3.14 => true
  • NaN => false
  • Infinity => false
  • null => false
  • undefined => false

isFinite() is almost perfect, but there's one gotcha: isFinite(null) returns true, when I actually want it to return false.

Short of always checking if ((val != nul) && isFinite(val)), is there another more concise technique?

atroberts20
  • 1,101
  • 7
  • 8

1 Answers1

5
// As suggested in the comments, a function:
var isNumber = function (val) {return !isNaN(parseInt(val))};
console.log(isNumber(1)) // true
console.log(isNumber(-42)) // true
console.log(isNumber(3.14)) // true
console.log(isNumber(NaN)) // false
console.log(isNumber(Infinity)) // false
console.log(isNumber(null)) // false
console.log(isNumber(undefined)) // false
Jonathan Gray
  • 2,509
  • 15
  • 20
  • 1
    You may even want to write a `isNumber` function: `var isNumber = function (val) {return !isNan(parseInt(val))}` – royhowie Nov 14 '14 at 06:00