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.

3
  • 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. Commented Apr 15, 2020 at 14:40
  • Does this answer your question? Convert string to either integer or float in javascript Commented Apr 15, 2020 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. Commented Apr 15, 2020 at 14:55

2 Answers 2

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'))

Sign up to request clarification or add additional context in comments.

1 Comment

@Bergi well spotted. fixed.
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"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.