Skip to content
Advertisement

Converting hexadecimal to float in JavaScript

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);

All is well there. Now I want to convert it back to decimal.

But now I cannot write:

var orgno = parseInt(convno, 16);
alert(orgno);

As it doesn’t return the decimal part.

And I cannot use parseFloat, since per MDC, the syntax of parseFloat is

parseFloat(str);

It wouldn’t have been a problem if I had to convert back to int, since parseInt’s syntax is

parseInt(str [, radix]);

So what is an alternative for this?

Disclaimer: I thought it was a trivial question, but googling didn’t give me any answers.

This question made me ask the above question.

Advertisement

Answer

Another possibility is to parse the digits separately, splitting the string up in two and treating both parts as ints during the conversion and then add them back together.

function parseFloat(str, radix)
{
    var parts = str.split(".");
    if ( parts.length > 1 )
    {
        return parseInt(parts[0], radix) + parseInt(parts[1], radix) / Math.pow(radix, parts[1].length);
    }
    return parseInt(parts[0], radix);
}

var myno = 28.4382;
var convno = myno.toString(16);
var f = parseFloat(convno, 16);
console.log(myno + " -> " + convno + " -> " + f);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement