0

I Want to convert Hexadecimal to Float 32. I have used below mention code but it didn't help me proper as I try to convert 0x4145851f this value to float32 it comes as a 12.345000267028809 But actually the value is 12.345 so I want to ignore extra digits. not rounding off, need proper output.

const HexToFloat32 = (str) => {
  var int = parseInt(str, 16);
  if (int > 0 || int < 0) {
    var sign = int >>> 31 ? -1 : 1;
    var exp = ((int >>> 23) & 0xff) - 127;
    var mantissa = ((int & 0x7fffff) + 0x800000).toString(2);
    var float32 = 0;
    for (let i = 0; i < mantissa.length; i += 1) {
      float32 += parseInt(mantissa[i]) ? Math.pow(2, exp) : 0;
      exp--;
    }
    return float32 * sign;
  } else return 0;
};

console.log(HexToFloat32("0x41200000"));

I already go through with below mention Stack URL:

stackoverflow.com/questions/5055723/converting-hexadecimal-to-float-in-javascript

Urvi_204
  • 2,308
  • 2
  • 10
  • 23
  • 1
    *"But actually the value is 12.345..."* No, actually the value is 12.345000267028809 (or very near it). So basically, you're asking how to do rounding to three places. – T.J. Crowder Apr 22 '22 at 10:04
  • 1
    [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript), [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Andreas Apr 22 '22 at 10:05
  • 1
    Side note: I'd probably use `Uint32Array` and a `Float32Array` sharing the same `ArrayBuffer` to do this, rather than a bunch of `parseInts`: https://jsfiddle.net/tjcrowder/fw8ebhpr/ :-) – T.J. Crowder Apr 22 '22 at 10:08
  • Yes @T.J.Crowder, but in more specific way – Urvi_204 Apr 22 '22 at 11:56

0 Answers0