1

I'm trying to do error handling on 2 input values. I'm using regex to confirm that the input is always a number. The issue I'm having is that I don't want my error handling to kick in if the user literally inputs 0. Right now I'm using:

number = parseInt(incomingValue) || ""

to set my variable. The issue is that this turns '0' into ""

Its fine if an empty value becomes an empty string because I am disabling my error checking when the lengths are equal to 0, but I need to properly turn '0' into a number 0. Anyone have any ideas?

Additionally, I'd also like to turn '000' (and so forth) into a number 0

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Joe Schmoe
  • 31
  • 3
  • 6
  • Does this answer your question? [Convert a string to an integer?](https://stackoverflow.com/questions/1133770/convert-a-string-to-an-integer) – 0stone0 Apr 01 '20 at 23:11

4 Answers4

4

You can turn '0' or '000' into a number by just doing:

parseInt('0');   // 0
parseInt('000'); // 0

The reason your code is not working is that javascript treats 0 as a falsly value, so when you do this:

const number = parseInt('0') || ""

the expression parseInt('0') will return 0 which is falsy. As a result, the || "" will be executed which will set number to "". You'll need to separate your parseInt and your default assignment to achieve what you want.

Mark
  • 9,718
  • 6
  • 29
  • 47
1

Use "Number()":

console.log(Number('0'));
console.log(Number('000'));

console.log(typeof(Number('0')));
console.log(typeof(Number('000')));

Or put "+" before '0' and '000':

console.log(+'0');
console.log(+'000');

console.log(typeof(+'0'));
console.log(typeof(+'000'));

Or put "* 1" before or after '0' and '000':

console.log('0' * 1);
console.log('000' * 1);

console.log(typeof('0' * 1));
console.log(typeof('000' * 1));
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
0

You can use parseInt(incomingValue) to get the int value. For comparing you can use === for equal value and equal type means (incomingValue === 0) will be true in case of incomingValue = 0.

Captain Jack Sparrow
  • 971
  • 1
  • 11
  • 28
0

You can try typeof to distinguish what type of variable you are receiving

typeof true === 'boolean'

typeof null === 'object'

typeof 62 === 'number'

typeof 'Hello World' === 'string'

Janneck Lange
  • 882
  • 2
  • 11
  • 34