1

Messing around with reversing a number from an Angular input.

Here is the method and property:

reversedIntInput = "";

  reverseInt(event: any) {
    const inputString = (<HTMLInputElement>event.target).value;
    const parsed = parseInt(inputString);

    if (Number.isNaN(parsed) || inputString == "" || inputString === null) {
      this.reversedIntInput = "Nice try but this is not a number.";
    } else {
      this.reversedIntInput = inputString
        .split("")
        .reverse()
        .join("");
    }
  }

and here is the html:

<label>Reverse an Integer</label>
<input type="text" class="form-control" (input)="reverseInt($event)">
<p>{{ reversedIntInput }}</p>

If I type "d" in the input, it does indeed display "Nice try but this is not a number." if I type "45" in the input it does indeed display "54".

But if I type "54ddd" it just reverses it as a string and displays "ddd45" when it should display "Nice try but this is not a number."

Why is that? I console log both inputString and parsed and inputString continues to update when a letter is typed but parsed does not.

Khepf
  • 352
  • 1
  • 4
  • 24
  • Add keydown event and when is pressed take ASCII code on pressed key, then check if asci code is >= 48 && <= 57, if is not event.preventDefault() to stop propagation or just return – Andon Mitev Feb 26 '20 at 20:34

2 Answers2

1

That happens because parseInt returns a valid Number if you pass a string that starts with a number. It just ignores what comes after the number:

const inputString = '54ddd';
const parsed = parseInt(inputString);

console.log(parsed); // prints 54

So when you are checking Number.isNaN(parsed) in this case, it will return false, because 54 is a valid Number.

Instead of Number.isNaN, you can use isNaN directly on your string (inputString), and it will work as you expect (yes, Number.isNan and isNan are different functions):

if (isNaN(inputString) || inputString == "" || inputString === null) {

When calling isNan on a string that is not entirely a number (even if it starts with one), it returns true:

const inputString = '54ddd';

console.log(isNaN(inputString)); // prints true
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46
1

Simply check inputString have value and that value is a number, see this:

if (inputString  && Number(inputString)) {
   this.reversedIntInput = reverse logic .....
} else {
  this.reversedIntInput = "Nice try but this is not a number.";
}
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85