Converting hexadecimal to float in JavaScript

前端 未结 7 1517
抹茶落季
抹茶落季 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:06

    Here is a size-improvement of Mark Eirich's answer:

    function hex2dec(hex) {
      let h = hex.split(/\./);
      return ('0x'+h[1])*(16**-h[1].length)+ +('0x'+h[0]);
    }
    

    function hex2dec(hex) {
      let h = hex.split(/\./);
      return ('0x'+h[1])*(16**-h[1].length)+ +('0x'+h[0]);
    }
    
    function calc(hex) {
      let dec = hex2dec(hex);
      msg.innerHTML = `dec: <b>${dec}</b><br>hex test: <b>${dec.toString(16)}</b>`
    } 
    
    let init = "bad.a55";
    inp.value = init;
    calc(init);
    <input oninput="calc(this.value)" id="inp" /><div id="msg"></div>

    0 讨论(0)
提交回复
热议问题