Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hexadecimal to float in JavaScript

Tags:

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.

like image 342
naveen Avatar asked Feb 20 '11 07:02

naveen


People also ask

How to convert hexadecimal to decimal in JavaScript?

The best way to convert a hexadecimal number to decimal is to make use of the parseInt() function. The parseInt() function takes a string as an argument and returns an integer. parseInt(string, radix); The first argument of it is the string to be converted, and the second argument is the radix (base) of the number.

How do you use hexadecimal in JavaScript?

Uses of Hexadecimal Numbers in JavaScriptJavaScript supports the use of hexadecimal notation in place of any integer, but not decimals. As an example, the number 2514 in hex is 0x9D2, but there is no language-supported way of representing 25.14 as a hex number.

How do you convert a floating number to hexadecimal?

Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.


3 Answers

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);
like image 184
Kent Avatar answered Sep 27 '22 19:09

Kent


Try this.

The string may be raw data (simple text) with four characters (0 - 255) or a hex string "0xFFFFFFFF" four bytes in length.

jsfiddle.net

var str = '0x3F160008';

function parseFloat(str) {
    var float = 0, sign, order, mantissa, exp,
    int = 0, multi = 1;
    if (/^0x/.exec(str)) {
        int = parseInt(str, 16);
    }
    else {
        for (var i = str.length -1; i >=0; i -= 1) {
            if (str.charCodeAt(i) > 255) {
                console.log('Wrong string parameter');
                return false;
            }
            int += str.charCodeAt(i) * multi;
            multi *= 256;
        }
    }
    sign = (int >>> 31) ? -1 : 1;
    exp = (int >>> 23 & 0xff) - 127;
    mantissa = ((int & 0x7fffff) + 0x800000).toString(2);
    for (i=0; i<mantissa.length; i+=1) {
        float += parseInt(mantissa[i]) ? Math.pow(2, exp) : 0;
        exp--;
    }
    return float*sign;
}
like image 42
Asler Avatar answered Sep 27 '22 20:09

Asler


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: <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>
like image 38
Mark Eirich Avatar answered Sep 27 '22 18:09

Mark Eirich