convert decimal to hexadecimal in javascript

How to Convert Decimal to Hexadecimal in JavaScript

Often colors and other codes are represented using hexadecimal strings. Sometimes you may need to convert decimal numbers or strings into hexadecimal strings. In this article, we will learn how to convert decimal to hexadecimal in JavaScript.


How to Convert Decimal to Hexadecimal in JavaScript

You can easily convert any decimal or string to hexadecimal using toString() function.

var num = 255;
hexString = num.toString(16); //returns ff

Please remember to include 16 in toString() function to convert decimal to hex system.

On the other hand if you want to convert hex string into decimal, you can do it using parseInt() function.

num2 = parseInt(hexString, 16); //returns 255

In this article, we have learnt how to convert decimal to hexadecimal. You can use this to easily convert decimal color code to hexadecimal color codes. Here is an example to convert rgb to hex color code.

function rgb_to_hex(r, g, b){
   return '#'+ r.toString(16) + g.toString(16) + b.toString(16);
}

Also read:

How to Add 30 Minutes to Date Object in JS
How to Measure Time Taken by JS Function
How to Replace Part of String in Update Query
How to View Live MySQL Queries
How to Generate Random String in MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *