Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isNaN() javascript, number with 2 commas

I'm working with percentage and the setInterval() so I have a

    var intervalId;
    function randomize(){
       var prc = $("#prc").val();
       var c = 0 ;
       if (!intervalId){
          intervalId = setInterval(function(){
              c = c + 1;
              var attempt = Math.random() * 100;
              if (attempt <= prc){
                  clearInterval(intervalId);
                  intervalId = false;
                  $("#attemptnbr").val(c);
              }
          }, 100);
       }
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Percentage : <input type="text" id="prc"/>
<button onclick="randomize()">GO</button>
Number of attempts :<input type="text" id="attemptnbr"/>

But actually if the user set the #prc input to 50.345.34, the attempt <= prc condition always returns true. I tried to console.log(isNaN(prc)) when this input is set to a number like 50.345.34 and it always returns false.

Why is it considered as a numeric value?

like image 367
Terry Rapt Avatar asked Sep 22 '15 08:09

Terry Rapt


Video Answer


1 Answers

But actually if the user set the #prc input to 50.345.34, the attempt <= prc condition always returns true.

Pretty sure that's observation error. Your prc is a string, which will then be implicitly converted to a number by the <= operator. The number will be NaN because "50.345.34" can't be implicitly converted, and relations using NaN are never true.

However it doesn't really change what you want to do about it, which is convert prc to a number on purpose and test the result:

var intervalId;
function randomize(){
   var prc = +$("#prc").val();
   //        ^------------------- Note the +, that converts it to a number
   if (isNaN(prc)) {
       // Handle the invalid input
       return;
   }
   var c = 0 ;
   if (!intervalId){
      intervalId = setInterval(function(){
          c = c + 1;
          var attempt = Math.random() * 100;
          if (attempt <= prc){
              clearInterval(intervalId);
              intervalId = false;
              console.log(attempt);
          }
      }, 100);
   }
}

I should note that the above may do something you don't want if the input is empty: It will use the value 0, because +"" is 0. If you don't want that, you might do this:

var prcString = $.trim($("#prc").val());
var prc = +prcString;
if (!prcString) {
    // Handle the fact they didn't enter anything
    return;
}
if (isNaN(prc)) {
    // Handle the invalid input
    return;
}
like image 133
T.J. Crowder Avatar answered Nov 02 '22 06:11

T.J. Crowder