Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to format hexadecimal Number in JavaScript?
JavaScript provides several methods to format hexadecimal numbers. The most common approach is using toString(16) to convert numbers to hexadecimal format, then applying padding and formatting as needed.
Basic Hexadecimal Conversion
The toString(16) method converts a number to its hexadecimal representation:
<!DOCTYPE html>
<html>
<body>
<script>
let num = 255;
let hex = num.toString(16);
document.write("Number: " + num + "<br>");
document.write("Hexadecimal: " + hex);
</script>
</body>
</html>
Number: 255 Hexadecimal: ff
Formatting with Leading Zeros
To format hexadecimal numbers with leading zeros, you can pad the string to a specific length:
<!DOCTYPE html>
<html>
<body>
<script>
let num = 32122;
let myHex = ("000000000000000" + num.toString(16)).substr(-16);
document.write("Number: " + num + "<br>");
document.write("16-digit hex: " + myHex);
</script>
</body>
</html>
Number: 32122 16-digit hex: 0000000000007d7a
Adding Dashes for UUID-like Format
You can format hexadecimal numbers with dashes to create UUID-like patterns:
<!DOCTYPE html>
<html>
<body>
<script>
let num = 32122;
let myHex = ("000000000000000" + num.toString(16)).substr(-16);
let resHex = myHex.substr(0, 8) + '-' + myHex.substr(8, 4) + '-' + myHex.substr(12, 4);
document.write("Original number: " + num + "<br>");
document.write("Formatted hex: " + resHex);
</script>
</body>
</html>
Original number: 32122 Formatted hex: 00000000-0000-7d7a
Using padStart() Method
Modern JavaScript provides the padStart() method for cleaner padding:
<!DOCTYPE html>
<html>
<body>
<script>
let num = 4095;
let hex = num.toString(16).padStart(8, '0').toUpperCase();
document.write("Number: " + num + "<br>");
document.write("8-digit uppercase hex: " + hex);
</script>
</body>
</html>
Number: 4095 8-digit uppercase hex: 00000FFF
Comparison of Methods
| Method | Browser Support | Readability |
|---|---|---|
| substr() with padding string | All browsers | Less readable |
| padStart() | ES2017+ | More readable |
Conclusion
Use toString(16) for basic hex conversion and padStart() for modern padding. For older browser support, use the string concatenation method with substr().
Advertisements
