20

I have this function :

 $scope.SearchTicketEvent = function (ticketPinOrEvent)
            {
                if (ticketPinOrEvent != undefined)
                {

                 if (ticketPinOrEvent.length == 10)
                    {

                     $scope.PinTicketSearch(ticketPinOrEvent);

                    }
                }


            }

How can i check if ticketPinOrEvent is number ? I tried with angular.isNumber(ticketPinOrEvent) but i dont get anything?

uzhas
  • 895
  • 4
  • 13
  • 27
  • what are you getting when you call angular.isNumber ? – dhavalcengg Jul 22 '15 at 08:51
  • Did you mean type `int` or `float`? – Vineet Jul 22 '15 at 08:52
  • @dhavalcengg when i try with console log if i enter 1234567890 i get false – uzhas Jul 22 '15 at 08:54
  • 1
    `angular.isNumber(1234567890)` => `true`. Check the value of your argument `ticketPinOrEvent`, which maybe `undefined`. – Joy Jul 22 '15 at 08:55
  • @ShaojiangCai its not undefined...it i enter like u hardcoding number i get true but when i pass like parameters i get false – uzhas Jul 22 '15 at 09:00
  • possible duplicate of [How to check that a number is float or integer?](http://stackoverflow.com/questions/3885817/how-to-check-that-a-number-is-float-or-integer) – Vineet Jul 22 '15 at 09:00

3 Answers3

45

If you want to use angular.isNumber

    if ( !isNaN(ticketPinOrEvent) && angular.isNumber(+ticketPinOrEvent)) {
    }
dhavalcengg
  • 4,678
  • 1
  • 17
  • 25
8

In Angular 6 this works without using any prefix.

Example:

if(isNumber(this.YourVariable)){
    // your Code if number
}
else {
    // Your code if not number
}
MarmiK
  • 5,639
  • 6
  • 40
  • 49
7

You might use the typeof to test if a variable is number.

if (typeof ticketPinOrEvent === 'number') {
    $scope.PinTicketSearch(ticketPinOrEvent);
}

Or might try this:

if (!isNaN(ticketPinOrEvent) && angular.isNumber(ticketPinOrEvent)) {
    $scope.PinTicketSearch(ticketPinOrEvent);
}

Testing against NaN:

NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.

Endre Simo
  • 11,330
  • 2
  • 40
  • 49
  • 1
    Angular 1.4.1 source code Line 628: `function isNumber(value) {return typeof value === 'number';}` – Joy Jul 22 '15 at 08:57