AniUI Academy

Format RGB channels as hex

easyDOM & Utilities+150 XPPractice

Colour pickers and interpolation code work in numbers, but CSS and <input type="color"> want #rrggbb. This conversion is where off-by-one padding bugs live: channel 1 must render as 01, not 1.

Implement rgbToHex(r, g, b). Each channel is first rounded with Math.round, then clamped into the range 0 to 255, then rendered as exactly two lowercase hex digits, zero-padded on the left.

Return the three channels concatenated after a single #, so the result is always exactly seven characters, lowercase — for example "#ff8800".

Arguments

rnumber
Red channel. Rounded and clamped into 0..255.
gnumber
Green channel. Rounded and clamped into 0..255.
bnumber
Blue channel. Rounded and clamped into 0..255.

Returns

string — A seven-character lowercase hex colour string in the form #rrggbb.

Examples

rgbToHex(255, 136, 0);
// => "#ff8800"

A normal in-range colour renders as six lowercase digits after #.

rgbToHex(1, 2, 3);
// => "#010203"

Single-digit channels are zero-padded to two digits each.

rgbToHex(300, -20, 12.6);
// => "#ff000d"

Fractions are rounded, and out-of-range values are clamped into 0..255.

What it has to do

  • Return a seven character string starting with #, using lowercase hex digits.
  • Zero-pad each channel to two digits.
  • Round fractional channel values with Math.round.
  • Clamp values below 0 to 0 and above 255 to 255.

Notes

  • Math.round uses banker's-free half-up rounding, so 0.5 becomes 1. If a caller cares about half-even rounding they must round the channels themselves before calling.
  • Lowercase matches what <input type="color"> emits via its .value property, so round-trips through the DOM compare with ===.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.