Converting hexadecimal to float in JavaScript

前端 未结 7 1530
抹茶落季
抹茶落季 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 14:43

    Try this:

    1. Decide how many digits of precision you need after the decimal point.
    2. Multiply your original number by that power of 16 (e.g. 256 if you want two digits).
    3. Convert it as an integer.
    4. Put the decimal point in manually according to what you decided in step 1.

    Reverse the steps to convert back.

    1. Take out the decimal point, remembering where it was.
    2. Convert the hex to decimal in integer form.
    3. Divide the result by the the appropriate power of 16 (16^n, where n is the number of digits after the decimal point you took out in step 1).

    A simple example:

    Convert decimal 23.5 into hex, and want one digit after the decimal point after conversion.

    23.5 x 16 = 376.

    Converted to hex = 0x178.

    Answer in base 16: 17.8

    Now convert back to decimal:

    Take out the decimal point: 0x178

    Convert to decimal: 376

    Divide by 16: 23.5

提交回复
热议问题