How to convert decimal to hexadecimal in JavaScript

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

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

27条回答
  •  灰色年华
    2020-11-21 23:41

    For anyone interested, here's a JSFiddle comparing most of the answers given to this question.

    And here's the method I ended up going with:

    function decToHex(dec) {
      return (dec + Math.pow(16, 6)).toString(16).substr(-6)
    }
    

    Also, bear in mind that if you're looking to convert from decimal to hex for use in CSS as a color data type, you might instead prefer to extract the RGB values from the decimal and use rgb().

    For example (JSFiddle):

    let c = 4210330 // your color in decimal format
    let rgb = [(c & 0xff0000) >> 16,  (c & 0x00ff00) >> 8,  (c & 0x0000ff)]
    
    // Vanilla JS:
    document..getElementById('some-element').style.color = 'rgb(' + rgb + ')'
    // jQuery:
    $('#some-element').css('color', 'rgb(' + rgb + ')')
    

    This sets #some-element's CSS color property to rgb(64, 62, 154).

提交回复
热议问题