1

I want to convert a string variable as follows:

  • the variable string is a float-> convert to float
  • else string is an integer-> convert to integer
  • else return string

This is what I currently tried:

function parse(x){
    return x==parseFloat(x)?parseFloat(x):
           x==parseInt(x)?parseInt(x):
           x
}

console.log(typeof parse("11.5"),parse("11.5"))
console.log(typeof parse("11"),parse("11"))
console.log(typeof parse("11.5A"),parse("11.5A"))

I am looking for solutions if there exists a more efficient and direct way to do this.

Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48
  • More direct? No. (Although `parseFloat` should suffice for parsing integers as well). More efficient? Don't call `parseFloat` and `parseInt` twice, but store the result in a temporary variable. – Bergi Apr 15 '20 at 14:40
  • Does this answer your question? [Convert string to either integer or float in javascript](https://stackoverflow.com/questions/33544827/convert-string-to-either-integer-or-float-in-javascript) – Mickael B. Apr 15 '20 at 14:42
  • Answers don't direct as mush as my try in the questions. Better be people try something from my try. That's why I posted this questions. – Nilanka Manoj Apr 15 '20 at 14:55

2 Answers2

0

const parse = x => !isNaN(x) ? Number(x) : x

console.log(parse(1), typeof parse(1))
console.log(parse(1.5), typeof parse(1.5))
console.log(parse('1'), typeof parse('1'))
console.log(parse('1A'), typeof parse('1A'))
console.log(parse(0), typeof parse(0))
console.log(parse('0'), typeof parse('0'))
lucas
  • 1,105
  • 8
  • 14
0

I found that this is more efficient:

function parse(x){
  return x==x*1?x*1:x
 }

function parse(x){
      return x==x*1?x*1:x
 }
console.log(typeof parse("11.5"),parse("11.5"))
console.log(typeof parse("11"),parse("11"))
console.log(typeof parse("11.5A"),parse("11.5A"))
Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48