0

I have an input which is always a String. The string can contain an integer or text:

intputString = "1";

or

inputString = "hey";

I would like to convert to a Number only those inputs that contain integers. Otherwise, the inputs need to remain the same.

For example, if I have an integer:

inputString = "288";          // <-- Make the conversion 
desiredOutput = 288;

And if I have non-integer text:

inputString = "hey";         // <-- Don't make the conversion and leave it as is
desiredOutput = "hey";

I was using Numbers(inputString) but this converts text values into NaN.

How can I achieve this conversion?

EDIT: None of the answers from the duplicate question answers this question.

robinCTS
  • 5,746
  • 14
  • 30
  • 37
Avión
  • 7,963
  • 11
  • 64
  • 105
  • you can check isNaN() before converting – Kiran Mar 07 '18 at 14:56
  • @Strikegently None of the answers of that post is valid for this one. – Avión Mar 07 '18 at 15:01
  • @MateuszJuruś what do you mean? `typeof("22") ` is still `string` and `typeof(NaN)` is still `number` – Ayush Gupta Mar 07 '18 at 15:02
  • How about those inputs: `-3`, `2.5`, `1e1` and `430583409583409583049`? Do you want them to be converted? – georg Mar 07 '18 at 15:06
  • @georg - The OP is correct that the supplied duplicate is not valid. Avión already knows how to convert a string into an integer. What is required is to keep the non-integer strings in their original state instead of being converted to `NaN`. (To be fair `isNaN` does appear once, but it is buried deeply in a long answer, and more as a footnote suggesting that it might be necessary, rather than in a supplied bit of code.) A *much* better dupe target would be [How do you check that a number is NaN in JavaScript?](//stackoverflow.com/questions/2652319). – robinCTS Mar 08 '18 at 05:58
  • @robinCTS: "convert a string to a number" is a topic most JS developers get wrong, mostly because there are quick and obvious (but inaccurate) ways to do that in the language. The referred thread has at least a few reasonable answers, e.g. https://stackoverflow.com/a/43050154/989121, the OP is welcome to study them and revisit their accepted solution later. – georg Mar 08 '18 at 06:57

2 Answers2

3

Simply cast the input to Number. If the result is NaN, return the original string, else return the casted value.

function convert(input) {
    if(input === "0") {
        return 0;
    }
    return Number(input) || input;
}

console.log(convert("288"));
console.log(convert("hey"));
console.log(convert("0"));
console.log(convert(""));
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
0

Maybe something like this:

if(!isNaN(inputString))
    output = inputString;
else
    //Input is not a number
Orry
  • 659
  • 6
  • 21