- agirorn / dec-2-hex-string.js
- How to Convert Decimal to Hex in JavaScript
- Number toString() method
- Call toString() on number literal
- Use Case: Convert RGB(A) to Hex
- 11 Amazing New JavaScript Features in ES13
- Convert dec to hex javascript
- # Table of Contents
- # Convert a number to Hexadecimal in JavaScript
- # Calling Number.toString() on a number literal
- # Parsing the hexadecimal value back to a number
- # Additional Resources
- Easily Convert Decimal to Hex in JavaScript Today
- Easily Convert Decimal to Hex in JavaScript Today
- Understanding Decimal and Hexadecimal
- Decimal System
- Hexadecimal System
- Converting Decimal to Hex in JavaScript
- Method 1: Using toString(16)
- Output:
- Method 2: Using parseInt() and toString()
- Output:
- Method 3: Using Bitwise Operators
- Output:
- Method 4: Using padStart Method
- Output:
- Conclusion
- FAQs
agirorn / dec-2-hex-string.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
function dec2hexString ( dec ) |
return ‘0x’ + ( dec + 0x10000 ) . toString ( 16 ) . substr ( — 4 ) . toUpperCase ( ) ; |
> |
But this code can only handle numbers not bigger than 65535 .
dec2hexString(65535) // => "0xFFFF" dec2hexString(65536) // => "0x0000" dec2hexString(65537) // => "0x0001"
JavaScript already offers a «native way» of doing it:
// our decimal number const nr = 999999999; // convert to hex const hex = nr.toString(16); // back to dec: const decNr = parseInt(hex, 16);
However, the example above can only handle numbers till Number.MAX_SAFE_INTEGER => 9007199254740991
const converter = require('hex2dec'); const hex = converter.decToHex("90071992547409919007199254740991"); // bigger than 9007199254740991 const dec = converter.hexToDec(hex); // => "90071992547409919007199254740991"
You have to use arrays if you still need bigger numbers :
How to Convert Decimal to Hex in JavaScript
In this article, we’re going to learn how to easily convert a decimal number to its hexadecimal equivalent in JavaScript. And we’ll look at some real-world scenarios where we’ll need to do this.
Number toString() method
To convert a decimal to hex in JavaScript, call the toString() method on the decimal, passing 16 as the radix argument, i.e., num.toString(16) . The toString() method will return the string representation of the number in hexadecimal form.
JavaScript Copied!
const num = 60; const hex = num.toString(16); console.log(hex); // 3c // Use parentheses when calling toString() directly const hex2 = (60).toString(16); console.log(hex2); // 3c
The Number toString() method returns the string representation of a number. If a base is specified with the first argument, the number is represented in that base. We pass 16 to use base 16, which is the hexadecimal base.
- 0 to 9 to represent values 0 to 9
- a to f ( A to F ) to represent values 10 to 16 . The letters are case-insensitive, so 3C2b is exactly the same value as 3c2B .
Call toString() on number literal
If you call toString() on a number literal directly, ensure you wrap it in parentheses ( ( ) ) or use two dots ( .. before toString() :
JavaScript Copied!
// Use parentheses const hex2 = (60).toString(16); console.log(hex2); // 3c // Use double dots const hex3 = 50..toString(16); console.log(hex3); // 32
If you use only one dot without parentheses, the JavaScript parser treats it as part of the number literal – a decimal point – instead of a member access operator.
JavaScript Copied!
console.log(40.); // 40 console.log(20.); // 20
So there will be an error, since there will be no member access operator before the member name.
JavaScript Copied!
// SyntaxError console.log(40.toString(16)); // SyntaxError console.log(20.toString(16));
So you wrap the number in parentheses so that everything outside them are seen as separate from the number.
JavaScript Copied!
console.log((40).toString(16)); // 28 console.log((20).toString(16)); // 14
Or you add a second dot that will be seen as the member access operator.
JavaScript Copied!
console.log(40..toString(16)); // 28 console.log(20..toString(16)); // 14
Use Case: Convert RGB(A) to Hex
One common use for converting decimal values to hex to convert a RGB color code to its hex equivalent. Here’s how we can do it:
JavaScript Copied!
function decToHex(dec) < return dec.toString(16); >function padToTwo(str) < return str.padStart(2, '0'); >function rgbToHex(r, g, b) < const hexR = padToTwo(decToHex(r)); const hexG = padToTwo(decToHex(g)); const hexB = padToTwo(decToHex(b)); return `#$$$`; > console.log(rgbToHex(255, 128, 237)); // #ff80ed console.log(rgbToHex(195, 151, 151)); // #c39797 console.log(rgbToHex(16, 16, 16)); // #0f0f0f
We create a reusable rgbToHex() function to convert the RGB code to its hex equivalent.
We use the padToTwo() function to pad a hex code to two digits, e.g, f -> 0f .
After converting the R , G , and B decimal values to their hexadecimal representations, we join them together in a string prefixed with the # character to form the hex color code.
We could modify the function to also accept RGBA values, where the A is a percentage value (between 0 and 1) used to specify color opacity. A will be the first two characters of the hex color code, having a value between 00 (0 or 0%) and ff (255 or 100%)
JavaScript Copied!
function decToHex(dec) < return dec.toString(16); >function padToTwo(str) < return str.padStart(2, '0'); >function rgbToHex(r, g, b, a) < const hexR = padToTwo(decToHex(r)); const hexG = padToTwo(decToHex(g)); const hexB = padToTwo(decToHex(b)); // Set "a" to 1 if not specified const aAbsolute = Math.round((a ?? 1) * 255); const hexA = padToTwo(decToHex(aAbsolute)); return `#$$$$`; > console.log(rgbToHex(255, 128, 237)); // #ffff80ed console.log(rgbToHex(195, 151, 151, 0.5)); // #80c39797 console.log(rgbToHex(16, 16, 16, 0.69)); // #b0101010
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.
Convert dec to hex javascript
Last updated: Jan 7, 2023
Reading time · 2 min
# Table of Contents
# Convert a number to Hexadecimal in JavaScript
To convert a number to hexadecimal, call the toString() method on the number, passing it 16 as the base, e.g. num.toString(16) .
The toString method will return the string representation of the number in hexadecimal form.
Copied!const num = 42; // ✅ Convert to Hex const hex = num.toString(16); console.log(hex); // 👉️ "2a" // ✅ Use parentheses when calling toString directly const hex2 = (42).toString(16); console.log(hex2); // 👉️ "2a" // ✅ Parse back to number const parsed = parseInt(hex, 16); console.log(parsed); // 👉️ 42
The Number.toString() method formats the supplied number and returns its string representation.
The only argument we passed to the Number.toString method is the radix (the base for the conversion).
The hexadecimal numeral system uses 16 distinct symbols, so that’s the base value we should specify.
The hexadecimal system uses 16 symbols to represent numbers:
- «0» to «9» to represent values 0 to 9
- «a» to «f» ( A to F ) to represent values 10 to 15 . Note that the letters are case-insensitive, so 12AB and 12ab are considered the same value.
When a base of greater than 10 is provided to the toString method, the letters of the alphabet indicate the numerals greater than 9 .
For hexadecimal numbers (base 16) — the letters from a to f are used.
Copied!const hex1 = (10).toString(16); console.log(hex1); // 👉️ "a" const hex2 = (15).toString(16); console.log(hex2); // 👉️ "f"
# Calling Number.toString() on a number literal
If you call the Number.toString method directly on the number literal, you have to wrap it in parentheses.
Copied!// ✅ Use parentheses when calling toString directly const hex2 = (42).toString(16); console.log(hex2); // 👉️ "2a" // ⛔️ SyntaxError: Invalid or unexpected token const hex3 = 42.toString(16);
If you don’t wrap the numeric literal in parentheses, JavaScript treats the period as a decimal point.
Copied!console.log(5. === 5); // 👉️ true
# Parsing the hexadecimal value back to a number
If you need to parse the hexadecimal value back to a number, use the parseInt() function.
Copied!const num = 42; // ✅ Convert to Hex const hex = num.toString(16); console.log(hex); // 👉️ "2a" // ✅ Parse back to number const parsed = parseInt(hex, 16); console.log(parsed); // 👉️ 42
The parseInt function parses the supplied string argument and returns an integer of the specified radix .
The function takes the following 2 arguments:
Name | Description |
---|---|
string | A string starting with an integer |
radix | An integer between 2 and 36 that represents the radix |
The hexadecimal numeral system uses 16 distinct symbols, so that’s the radix
value we should specify.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Easily Convert Decimal to Hex in JavaScript Today
Hassan AbdElrahman
Easily Convert Decimal to Hex in JavaScript Today
As a developer, knowing how to work with different numeral systems is essential. One such system is hexadecimal, which is commonly used in web development. In JavaScript, there are several ways to convert decimal to hex. In this article, we will explore the different methods of converting decimal to hex in JavaScript.
Understanding Decimal and Hexadecimal
Before we dive into the different methods of converting decimal to hex in JavaScript, let’s first understand what decimal and hexadecimal are.
Decimal System
The decimal system is a base-10 numeral system that uses ten symbols (0-9) to represent numbers. Each digit in a decimal number represents a power of 10. For example, in the number 123, the digit 1 represents 100, the digit 2 represents 10, and the digit 3 represents 1.
Hexadecimal System
The hexadecimal system is a base-16 numeral system that uses 16 symbols (0-9 and A-F) to represent numbers. Each digit in a hexadecimal number represents a power of 16. For example, in the number 1F, the digit 1 represents 16, and the digit F represents 15.
Converting Decimal to Hex in JavaScript
Now that we understand decimal and hexadecimal let’s explore the different methods of converting decimal to hex in JavaScript.
Method 1: Using toString(16)
JavaScript provides a built-in method called toString() that can be used to convert a decimal number to a hexadecimal string. The method takes one parameter, which is the base of the numeral system we want to convert to. In this case, we want to convert to base-16, so we pass 16 as the parameter.
const decimal = 255; const hex = decimal.toString(16); console.log(hex);
Output:
Method 2: Using parseInt() and toString()
Another way to convert decimal to hex in JavaScript is by using the parseInt() and toString() methods. The parseInt() method can be used to convert a string to a decimal number, and the toString() method can be used to convert a decimal number to a string in a different base. In this case, we pass 16 as the second parameter to toString() to convert to base-16.
const decimal = 255; const hex = decimal.toString(16); console.log(hex);
Output:
Method 3: Using Bitwise Operators
A third method to convert decimal to hex in JavaScript is by using bitwise operators. Bitwise operators work by manipulating the binary representation of numbers. To convert decimal to hex using bitwise operators, we first convert the decimal number to a 32-bit binary number and then group the binary digits into four groups. Each group represents a hexadecimal digit.
const decimal = 255; const hex = (decimal + 0x10000).toString(16).substr(-2); console.log(hex);
Output:
Method 4: Using padStart Method
A fourth method to use the String.prototype.padStart() method. This method pads the start of a string with a specified character until it reaches a certain length. By passing in 0 as the pad character, we can pad the start of the resulting string with zeroes until it reaches a certain length. This method works for both decimal and fractional parts of the number.
let decimalNumber = 255; let hexNumber = decimalNumber.toString(16).padStart(2, '0'); console.log(hexNumber);
Output:
Conclusion
In this article, we explored the different methods of converting decimal to hex in JavaScript. We learned about the decimal and hexadecimal numeral systems and how to convert between them using JavaScript’s built-in methods and bitwise operators. As a developer, it’s essential to understand these concepts and be able to work with different numeral systems.
FAQs
- What is the decimal system?
- The decimal system is a base-10 numeral system that uses ten symbols (0-9) to represent numbers.
- What is the hexadecimal system?
- The hexadecimal system is a base-16 numeral system that uses 16 symbols (0-9 and A-F) to represent numbers.
- How can I convert a decimal number to hex in JavaScript?
- You can convert a decimal number to hex in JavaScript using built-in methods such as toString(16) or parseInt() and toString(). You can also use bitwise operators to perform the conversion.
- Can I convert a hex number to a decimal in JavaScript?
- Yes, you can convert a hex number to a decimal in JavaScript using the parseInt() method. You can pass the hex number as the first parameter and the base of the numeral system (16) as the second parameter.
- Why is it important to be able to work with different numeral systems as a developer?
- Working with different numeral systems is essential for developers who work with computer systems, networks, and web development. It enables them to manipulate and work with data more efficiently and effectively. Understanding different numeral systems is also a fundamental concept in computer science and programming.