Skip to content

Instantly share code, notes, and snippets.

@mlocati
Last active June 13, 2026 23:21
Show Gist options
  • Select an option

  • Save mlocati/7210513 to your computer and use it in GitHub Desktop.

Select an option

Save mlocati/7210513 to your computer and use it in GitHub Desktop.
Javascript color scale from 0% to 100%, rendering it from red to yellow to green
// License: MIT - https://opensource.org/licenses/MIT
// Author: Michele Locati <michele@locati.it>
// Source: https://gist.github.com/mlocati/7210513
function perc2color(perc) {
var r, g, b = 0;
if(perc < 50) {
r = 255;
g = Math.round(5.1 * perc);
}
else {
g = 255;
r = Math.round(510 - 5.10 * perc);
}
var h = r * 0x10000 + g * 0x100 + b * 0x1;
return '#' + ('000000' + h.toString(16)).slice(-6);
}
@quozl

quozl commented Jun 13, 2026

Copy link
Copy Markdown

Tracked a bug down in my own code related to this gist, if perc is not a number, you get NaN in the output. Adding this as a defense and modernising;

function perc2color(perc) {
    let cleanPerc = parseFloat(perc);
    if (isNaN(cleanPerc)) cleanPerc = 0;

    cleanPerc = Math.max(0, Math.min(100, cleanPerc));

    let r = 0, g = 0, b = 0;
    if (cleanPerc < 50) {
        r = 255;
        g = Math.round(5.1 * cleanPerc);
    } else {
        g = 255;
        r = Math.round(510 - 5.10 * cleanPerc);
    }
    
    const h = (r << 16) + (g << 8) + b;
    return '#' + h.toString(16).padStart(6, '0');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment