2

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?

0

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I modifier my code with your code but I haven't any result , and when i entering a number value i haven't any result also
okey now when i entering a number value i have message invalid saisie :(
0

The problem is in the if statement, apply parseFloat before typeof operator, so replace:

typeof ($scope.test) !== 'number'

To:

(typeof (parseFloat($scope.test)) !== 'number')

1 Comment

Thank you to all to be of help me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.