Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting RGB to HEX issue

according to one of StackOverflow topics I tried to create own RGB to HEX colors converter.

I don't know why but instead converting it double RGB numbers.

So when input is rgb(0, 128, 192) it console out #00128192.

My code is:

fromRGB: {
    toHEX: {
        supportFunc: function(number) {
            var hex = number.toString(16);
            return hex.length == 1 ? '0' + hex : hex;
        },
        convert: function(r, g, b) {
            var lol = '#' + this.supportFunc(r) + this.supportFunc(g) + this.supportFunc(b);
            console.log(lol);
        }
    },
    prepareAndExecute: function(color_field) {
        // preparing
        var numbers = color_field.match(/\d+/g);
        if(numbers.length == 3) {
            this.toHEX.convert(numbers[0], numbers[1], numbers[2]);
        } else {
            alert('wrong RGB number format');
        }


        //this.toHSL(preparedValue);
    }
}

I execute prepare function, lol variable is the one that should contains converted color in HEX format.

What is wrong with my code, why it doesn't work?

like image 587
BT101 Avatar asked Feb 17 '26 07:02

BT101


1 Answers

Explanation:

It's because you're passing strings not numbers to supportFunc.

The result of match in prepareAndExecute is an array of strings, thus when you call toString in supportFunc, you are calling String.prototype.toString (not Number.prototype.toString) which return the string as is.

Solution:

In supportFunc, convert number to a number before using toString:

var hex = Number(number).toString(16);                       // using Number to convert a string to a number (you can use parseInt or unary + if you like)

or convert them before passing them to convert:

this.toHEX.convert(+numbers[0], +numbers[1], +numbers[2]);   // using unary +
like image 183
ibrahim mahrir Avatar answered Feb 18 '26 20:02

ibrahim mahrir