0

Simple Question: How to test if a variable is referencing a number in coffeescript? Could not find an answer in the docs.

Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147
  • 2
    I think you can try to use this answers http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric ```isNumber: (n) -> not isNaN(parseFloat(n)) and isFinite(n)``` – Pavel Komiagin Apr 16 '15 at 14:56
  • I dont understand `not isNaN(parseFloat(n) and isFinite`. Shouldn't your method return some value to the method caller? – Stephan Kristyn Apr 16 '15 at 15:00
  • Hmm it's a function :) Could you explain please what's wrong? – Pavel Komiagin Apr 16 '15 at 15:03
  • Did not know that you can ommit `return` in coffeescript. Anyhow, your function typecasts a String to a Number, thus it is worthless. – Stephan Kristyn Apr 16 '15 at 15:09

3 Answers3

2

Strictly speaking, you can test variable type (which seems to be what you're asking) with

typeof n is 'number' and isFinite n

Note that this doesn't convert strings, etc., just checks straight up whether it's already a finite number.

Tyler
  • 11,272
  • 9
  • 65
  • 105
0

If you're not against using libraries, underscore/lodash provide great utility functions.

_.isNumber or _.isFinite (depending on if you want Infinity, and NaN to be categorized as numbers)

dule
  • 17,798
  • 4
  • 39
  • 38
-1

You can have a global function: isNumber: (n) -> return not isNaN(parseFloat(n)) and isFinite(n) and use it: is_number = isNumber('123') it returns true if argument is not NaN and is not a infinity. Otherwise returns false

Pavel Komiagin
  • 708
  • 6
  • 10