How to convert decimal to hexadecimal in JavaScript

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

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

27条回答
  •  名媛妹妹
    2020-11-21 23:31

    If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The JavaScript function toString(16) will return a negative hexadecimal number which is usually not what you want. This function does some crazy addition to make it a positive number.

    function decimalToHexString(number)
    {
      if (number < 0)
      {
        number = 0xFFFFFFFF + number + 1;
      }
    
      return number.toString(16).toUpperCase();
    }
    
    console.log(decimalToHexString(27));
    console.log(decimalToHexString(48.6));

提交回复
热议问题