How to use Number() Function In Javascript
In this approach, we will use the built-in JavaScript function Number() to convert the concatenated string to a decimal number. JavaScript recognizes the hexadecimal format when the “0x” prefix is present inside the Number() function. We will return the decimal equivalent of the hexadecimal input.
Example: Demonstration of converting hexadecimal to decimal using the Number() function.
function hexaToDeci(hex) {
// Using Number() function with base 16
return Number(`0x${hex}`);
}
// hexadecimal string
const hexadecimalNumber = "1A";
const decimal = hexaToDeci(hexadecimalNumber);
console.log("Decimal equivalent of ",
hexadecimalNumber, "is ", decimal);
Output
Decimal equivalent of 1A is 26
Time Complexity: O(n).
Space Complexity: O(1).
JavaScript Program to Convert Hexadecimal to Decimal
Decimal numbers are a base 10 number system which uses 10 digits from 0 to 9 and hexadecimal numbers are a base 16 number system which uses 16 digits, numbers from 0 to 9, and letters from A to F. We are given a hexadecimal number as input we have to convert it into decimal in JavaScript and print the result.
Example:
Input: 1A
Output: 26
Below are the methods to convert Hexadecimal to Decimal:
Table of Content
- Using parseInt() Function
- Using Number() Function
- Using Iterative Method