isNaN() returns false for anything that starts with a number, even if it contains letters

1823 views javascript
-1

The program I made is supposed to take a number in a selected numeral system and convert it into the number of the same value in the other selected system. It is much bigger but I gave you the simple version with already selected system you want to convert from and to.

It is supposed to give you an error message (Please enter a proper ${fromSystem[1]} number) if the entered number is not a proper number. But if a number starts with numbers and later contains letters, it thinks it is a number. Everything after the number is ignored (example: for 25ad3 it would convert 25 and ignore everything after it). You can test it (this code has the functionality).

Anyone know how to fix this?

Edit: I just added more details

fromSystem = [10, "decimal"]; // Decimal
toSystem = [2, "binary"]; // Binary

$("#convert").click(function() {
          var result;
          var inputValue = $("#inputBox").val();
          if (fromSystem === toSystem) {
            result = inputValue;
          } else {
            result = parseInt(inputValue, fromSystem[0]).toString(toSystem[0]);
          }
          if (isNaN(result) === true) {
            result = `Please enter a proper ${fromSystem[1]} number`;
          } else {
            result = result.toUpperCase();
          }
          $("#resultPara").html(result);
        })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="converterArea">
      <input id="inputBox" type="text" placeholder="">
      <button id="convert" type="button">Convert</button>
      <p id="resultPara"></p>
    </div>

answered question

1 Answer

6

This is a desired behavior because of the way the isNaN is implemented, see the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Description

I would first test if it contains only numbers using regexp, like that:

fromSystem = [10, "decimal"]; // Decimal
toSystem = [2, "binary"]; // Binary

$("#convert").click(function() {
          var result;
          var inputValue = $("#inputBox").val();
          if (fromSystem === toSystem) {
            result = inputValue;
          } else {
            result = parseInt(inputValue, fromSystem[0]).toString(toSystem[0]);
          }
          if (inputValue.match(/[^0-9]/g)) {
            result = `Please enter a proper ${fromSystem[1]} number`;
          } else {
            result = result.toUpperCase();
          }
          $("#resultPara").html(result);
        })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="converterArea">
      <input id="inputBox" type="text" placeholder="">
      <button id="convert" type="button">Convert</button>
      <p id="resultPara"></p>
    </div>

posted this

Have an answer?

JD

Please login first before posting an answer.