Shantanu Banerjee
Shantanu Banerjee

Reputation: 1447

32 bit hex string to floating point number in java

I have the following string "0x4B196DAF". I want to get output like "10055087.000000".

My piece of code is showing a strange output like "1.0055087E7"

long l = Long.parseLong(hexval, 16);
return Float.intBitsToFloat(l.intValue()); 

I have also tried with

long l = Long.parseLong(hexval, 16);
return Double.longBitsToDouble(l.longValue());

But nothing helpful. I have check few website which showing the correct output. I can't find out the problem exactly.

Upvotes: 0

Views: 3731

Answers (1)

Laura Konda
Laura Konda

Reputation: 106

I assume you want to print it out as a string, call somewhere toString(). It will give a scientific notation after limit is met.

You can try to use:

int hex = 0x4B196DAF;
float f = Float.intBitsToFloat(hex);
System.out.println(f);
System.out.printf("%f", f);

Output ....

1.0055087E7
10055087.00000010055087

or if you want you can try using NumberFormat, which will allow you to set a minimum fraction digits:

NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
nf.setMinimumFractionDigits(6);

System.out.println(nf.format(f));

output ....

10055087.000000

I hope it will help.

Upvotes: 3

Related Questions