How to convert decimal to hexadecimal in JavaScript

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

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

27条回答
  •  星月不相逢
    2020-11-21 23:36

    Without the loop:

    function decimalToHex(d) {
      var hex = Number(d).toString(16);
      hex = "000000".substr(0, 6 - hex.length) + hex;
      return hex;
    }
    
    // Or "#000000".substr(0, 7 - hex.length) + hex;
    // Or whatever
    // *Thanks to MSDN
    

    Also isn't it better not to use loop tests that have to be evaluated?

    For example, instead of:

    for (var i = 0; i < hex.length; i++){}
    

    have

    for (var i = 0, var j = hex.length; i < j; i++){}
    

提交回复
热议问题