0
0
JavascriptHow-ToBeginner · 2 min read

JavaScript How to Convert Hexadecimal to Decimal Number

Use parseInt(hexString, 16) in JavaScript to convert a hexadecimal string to a decimal number, where hexString is your hex value.
📋

Examples

Input"1A"
Output26
Input"FF"
Output255
Input"0"
Output0
🧠

How to Think About It

To convert hexadecimal to decimal, think of the hex string as a number in base 16. You want to translate each hex digit into its decimal value and combine them according to their position. JavaScript's parseInt function can do this directly by specifying the base as 16.
📐

Algorithm

1
Get the hexadecimal string input.
2
Use a function that reads the string as base 16 number.
3
Convert and return the decimal equivalent.
💻

Code

javascript
const hexString = "1A";
const decimalNumber = parseInt(hexString, 16);
console.log(decimalNumber);
Output
26
🔍

Dry Run

Let's trace converting "1A" to decimal using parseInt.

1

Input hex string

hexString = "1A"

2

Call parseInt with base 16

parseInt("1A", 16) reads '1' as 1*16 + 'A' as 10

3

Calculate decimal value

1*16 + 10 = 26

Hex DigitDecimal ValueCalculation
111 * 16 = 16
A1010 * 1 = 10
Sum = 16 + 10 = 26
💡

Why This Works

Step 1: parseInt reads string as base 16

The parseInt function takes the string and base 16 to understand each character as a hex digit.

Step 2: Hex digits convert to decimal values

Each hex digit (0-9, A-F) is converted to its decimal equivalent (0-15).

Step 3: Combine digits by place value

Digits are multiplied by powers of 16 based on their position and summed to get the decimal number.

🔄

Alternative Approaches

Using Number constructor with '0x' prefix
javascript
const hexString = "1A";
const decimalNumber = Number("0x" + hexString);
console.log(decimalNumber);
This works well but requires adding '0x' prefix manually; parseInt is more flexible.
Using unary plus with '0x' prefix
javascript
const hexString = "1A";
const decimalNumber = +("0x" + hexString);
console.log(decimalNumber);
Similar to Number(), but unary plus is shorter; still needs '0x' prefix.

Complexity: O(n) time, O(1) space

Time Complexity

The function processes each character once, so time grows linearly with the length of the hex string.

Space Complexity

Only a few variables are used, so space is constant regardless of input size.

Which Approach is Fastest?

Using parseInt with base 16 is fast and clear; Number with '0x' prefix is similar but less flexible.

ApproachTimeSpaceBest For
parseInt(hexString, 16)O(n)O(1)General hex to decimal conversion
Number('0x' + hexString)O(n)O(1)Quick conversion with prefix added
Unary plus with '0x' prefixO(n)O(1)Short syntax but needs prefix
💡
Always specify base 16 in parseInt to avoid errors with hex strings.
⚠️
Forgetting to specify base 16 in parseInt causes wrong decimal conversion.