Converting hexadecimal to float in JavaScript

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

    I combined Mark's and Kent's answers to make an overloaded parseFloat function that takes an argument for the radix (much simpler and more versatile):

    function parseFloat(string, radix)
    {
        // Split the string at the decimal point
        string = string.split(/\./);
        
        // If there is nothing before the decimal point, make it 0
        if (string[0] == '') {
            string[0] = "0";
        }
        
        // If there was a decimal point & something after it
        if (string.length > 1 && string[1] != '') {
            var fractionLength = string[1].length;
            string[1] = parseInt(string[1], radix);
            string[1] *= Math.pow(radix, -fractionLength);
            return parseInt(string[0], radix) + string[1];
        }
        
        // If there wasn't a decimal point or there was but nothing was after it
        return parseInt(string[0], radix);
    }
    

提交回复
热议问题