IsNaN () javascript, two comma number

I work with percent and setInterval() , so I have

  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 in fact, if the user set the #prc input to 50.345.34 , the attempt <= prc condition always returns true . I tried 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 a numerical value?

+5
source share
2 answers

But in fact, if the user set the #prc input to 50.345.34, the try & lt = = prc condition always returns true.

Pretty sure the observation error. Your prc is a string that will then be implicitly converted to a number by the <= operator. The number will be NaN , because "50.345.34" cannot be implicitly converted, and relationships using NaN never true.

However, in reality this does not change what you want to do, which converts prc to a number with a goal and checks 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 can do what you do not need if the input is empty: it will use the value 0 , because +"" - 0 . If you do not want this, you can 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; } 
+7
source

Because $("#prc").val() returns a string. 50.345.34 is a string. When you compare string and number, js will compare string length and numeric value.

0
source

Source: https://habr.com/ru/post/1232006/


All Articles