Converting hexadecimal to float in JavaScript

前端 未结 7 1533
抹茶落季
抹茶落季 2020-11-28 14:14

I would like to convert a number in base 10 with fraction to a number in base 16.

var myno = 28.5;

var convno = myno.toString(16);
alert(convno);
         


        
7条回答
  •  甜味超标
    2020-11-28 15:00

    Please try this:

    function hex2dec(hex) {
        hex = hex.split(/\./);
        var len = hex[1].length;
        hex[1] = parseInt(hex[1], 16);
        hex[1] *= Math.pow(16, -len);
        return parseInt(hex[0], 16) + hex[1];
    }
    

    function hex2dec(hex) {
      hex = hex.split(/\./);
      var len = hex[1].length;
      hex[1] = parseInt(hex[1], 16);
      hex[1] *= Math.pow(16, -len);
      return parseInt(hex[0], 16) + hex[1];
    }
    
    
    
    // ----------
    // TEST
    // ----------
    
    function calc(hex) {
      let dec = hex2dec(hex);
      msg.innerHTML = `dec: ${dec}
    hex test: ${dec.toString(16)}` } let init="bad.a55"; inp.value=init; calc(init);

提交回复
热议问题