0

All of my inputs are strings. I want to export them to a sort of DB, using the correct type.

So I can have inputs like e.g. "hello123", "123", or "123.0".
Which have the type string, int, and float respectively.

I already have a decent function determining whether it's a number or not:

const isNumber = (input) => !isNaN(Number(input))

console.log(isNumber("123hello")) // false
console.log(isNumber("123"))      // true
console.log(isNumber("123.0"))    // true

But I would like something like:

const getType = (input) => {
  if (/* check if int */) {
    return 'int'
  } else if (/* check if float */) {
    return 'float'
  } else {
    return 'string'
  }
}

console.log(getType("123hello")) // 'string'
console.log(getType("123"))      // 'int'
console.log(getType("123.0"))    // 'float' (preferably, but 'int' is also ok)
Nermin
  • 749
  • 7
  • 17
  • `parseInt(input).toString() === input` then it's an integer `parseFloat(input).toString() === input` then it's a float otherwise it's a string – pawel May 06 '22 at 15:06
  • 1
    It's worth noting, even if only for future readers, that just because a string is only numbers doesn't make it "a number". Postal codes, phone numbers, social security numbers, certain record identifiers, etc. Semantic context, not the data value itself, is the only way to know if a string of numeric characters really should be a string or a number. – David May 06 '22 at 15:06
  • @pawel `parseFloat("3.20").toString() === "3.20"` – Lee Taylor May 06 '22 at 15:10
  • @pawel `parseFloat("123.0").toString() === "123.0"` is not true :/ because it will parse `123.0` to `123` – Nermin May 06 '22 at 15:12
  • `123.0` is an integer: https://en.wikipedia.org/wiki/Integer _"An integer (from the Latin integer meaning "whole") is colloquially defined as a number that can be written without a fractional component."_ `123.0 === 123` can be written without fractional component. Adding an unnecessary `.0` doesn't convert an integer to a non-integer – jabaa May 06 '22 at 15:23
  • @jabaa OK. But `parseInt("123.0").toString() === "123.0"` is still not true since parseInt will also strip the decimal. So the function would return 'string' – Nermin May 06 '22 at 15:27
  • Yes, that's what Lee Taylor wrote earlier. pawel's solution doesn't work. The accepted answer in the duplicate contains a working solution, that classifies `123.0` as integer and according to the Wikipedia link, that's correct. – jabaa May 06 '22 at 15:40
  • I finally got this working example https://jsfiddle.net/4q8mrw97/ – Nermin May 06 '22 at 15:43

0 Answers0