Reputation: 75
I created this code to check if value is number or not but it doesn't seem to work.
app.controller('ForCtrl', function($scope) {
$scope.calcul_factorielle = function() {
var mm = 1;
if ((typeof ($scope.test) !== 'number')) $scope.factorielle = " invalide saisie";
for(i=2;i<=$scope.test;i++) {
mm = mm * i;
}
$scope.factorielle = mm;
}
});
Why, when I'm entering string stackoverflow
am I not receiving the 'invalide saisie'
message in the output?
Upvotes: 2
Views: 94
Reputation: 22041
The problem is in the if statement, apply parseFloat before typeof
operator, so replace:
typeof ($scope.test) !== 'number'
To:
(typeof (parseFloat($scope.test)) !== 'number')
Upvotes: 0
Reputation: 68665
After this if
statement, if your text is not a number, you need to break the execution of the function with the keyword return
. In your case the code continues after the if
statement, so you get a wrong result.
For first you need to parse it into number
, because every input is a string
and after that then try to use isNaN()
function. If string can not be parsed to the number
it will return an NaN
.
var number = Number.parseInt($scope.test);
if (isNaN(number)) { // or i
$scope.factorielle = " invalide saisie";
return;
}
Upvotes: 2