This post will discuss how to convert a hex string to a number in JavaScript.

There are several methods to convert a hex string to a number in JavaScript, depending on the format of the hex string and the desired output of the integer. Here are some of the most common functions:

1. Using parseInt() function

One option is to use the parseInt() function, which is a global function that parses a string and returns an integer. The first argument to the parseInt() function must be a string and the second optional argument specifies the radix (base) of the number system to use. For hex strings, the radix should be 16. This method works for both positive and negative hex strings. For example, we can convert a hex string to a number using parseInt() like this:

Download  Run Code

 
Note that the function recognizes the prefix 0x or 0X as hexadecimal, so we can omit the radix argument in this case. However, it is recommended to always specify the radix argument to avoid confusion and errors.

Download  Run Code

2. Using Number() function

Another option is to use the Number() function, which converts any value to a number. This method will return a numeric value if the value can be converted to a number, and NaN (not a number) otherwise. For hex strings, the value should start with "0x" or "0X" to indicate that it is in hexadecimal format. This function also works for both positive and negative hex strings. For example, we can convert a hex string to a number using Number() like this:

Download  Run Code

3. Using unary plus operator

A third option is to use the unary plus operator (+), which converts its operand to a number and return NaN if the conversion is not feasible. If we use this operator with a hexadecimal value, it will return the corresponding decimal value. For example, we can convert a hex string to a number using + like this:

Download  Run Code

4. Using BigInt object

A fourth option is to convert the hex string to the BigInt object and then call its toString() function with a radix of 10. This function will convert the BigInt object to a decimal string. However, it will not handle the negative hex strings correctly and also requires a modern browser that supports BigInt. For example:

Download  Run Code

That’s all about converting a hex string to a number in JavaScript.