How to convert decimal to hexadecimal in JavaScript

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

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

27条回答
  •  逝去的感伤
    2020-11-21 23:39

    To sum it all up;

    function toHex(i, pad) {
    
      if (typeof(pad) === 'undefined' || pad === null) {
        pad = 2;
      } 
    
      var strToParse = i.toString(16);
    
      while (strToParse.length < pad) {
        strToParse = "0" + strToParse;
      }
    
      var finalVal =  parseInt(strToParse, 16);
    
      if ( finalVal < 0 ) {
        finalVal = 0xFFFFFFFF + finalVal + 1;
      }
    
      return finalVal;
    }
    

    However, if you don't need to convert it back to an integer at the end (i.e. for colors), then just making sure the values aren't negative should suffice.

提交回复
热议问题