1

I receive a string which can be a number '42' or an hexadecimal number '0x12'. I would like to convert this to a number.

I currently have this very cumbersome function:

function str2num(str) {
    if (str.substr(0, 2) == '0x')
        return parseInt(substr(2, str), 16)
    else 
        return parseInt(str, 10)
}

Is there a shorter way to do that?

1
  • 2
    maybe read the documentation of parseInt. It can do more than you seem to know. Commented Jan 19, 2020 at 11:52

1 Answer 1

3

If I understand properly you want convert anything to integer; so you can just use

parseInt('0x12'). It convert any type of variable to integer.

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

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.