DEV Community

Discussion on: Did you know there are 4 and 8 digit hex codes (#11223344?) for colours? 🀯

Collapse
 
valeriavg profile image
Valeria

Why in the world would you need a table to convert numbers to hex?)

Just open a browser console or type node in terminal and type:

(255).toString(16) // 255 => ff
// Or
(0.8*255).toString(16) // 80% => cc
Enter fullscreen mode Exit fullscreen mode
Collapse
 
grahamthedev profile image
GrahamTheDev

Great tip for a quick way of doing one off calculations. ❀

Why in the world would you need a table to convert numbers to hex?

If you are doing a design and working with say 10 elements that all need their opacity fine tuning a table is many times faster than writing (0.8*255).toString(16) then (0.75*255).toString(16) then (0.72*255).toString(16) etc. etc.

So tables certainly have their uses. πŸ‘

Collapse
 
valeriavg profile image
Valeria

Not convinced, another round?)

If I'd be fine-tuning 10 elements I'd use a browser color picker 😎

dev console color picker with opacity and conversions

Thread Thread
 
grahamthedev profile image
GrahamTheDev

TouchΓ©.

It is a good thing I added a "skip this long table" link then so people can get past it 🀣.

Thread Thread
 
valeriavg profile image
Valeria

Haha, true that :-)

Collapse
 
abhinav1217 profile image
Abhinav Kulshreshtha

Great tip. But an issue to this approach is fractional values

(0.30*255).toString(16)  //  "4c.8"
(0.38*255).toString(16) //   "60.e66666666668"
Enter fullscreen mode Exit fullscreen mode

So I have to be careful when using this technique to setting up dynamic color values in something like generating css using js params.

Rounding up hexadecimal values is a tricky business....

Collapse
 
valeriavg profile image
Valeria

If you need a quick manual conversion - you can simply ignore everything what comes after ..

Or you can use:

Math.round(0.30*255).toString(16) // 4d, rounds up for >=.5
Math.floor(0.30*255).toString(16) // 4c, rounds down
Math.ceil(0.30*255).toString(16) // 4d, rounds up
Enter fullscreen mode Exit fullscreen mode