How to convert decimal to hexadecimal in JavaScript

后端 未结 27 2599
臣服心动
臣服心动 2020-11-21 23:05

How do you convert decimal values to their hexadecimal equivalent in JavaScript?

27条回答
  •  醉话见心
    2020-11-21 23:36

    AFAIK comment 57807 is wrong and should be something like: var hex = Number(d).toString(16); instead of var hex = parseInt(d, 16);

    function decimalToHex(d, padding) {
        var hex = Number(d).toString(16);
        padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
    
        while (hex.length < padding) {
            hex = "0" + hex;
        }
    
        return hex;
    }
    

提交回复
热议问题