Hexadecimal & # 8594; Float conversion inaccurate

I use the following code to convert a hexadecimal String to a floating point String :

 private static String removeScientificNotation(float value) { return new BigDecimal(Float.toString(value)).toPlainString(); } /** * Converts a hexadecimal value to its single precision floating point representation * * @param hexadecimal The <code>hexadecimal</code> to convert * @return The converted value */ public static String hexadecimalToFloatingPoint(String hexadecimal) { Long longBits = Long.parseLong(hexadecimal, 16); Float floatValue = Float.intBitsToFloat(longBits.intValue()); return removeScientificNotation(floatValue); } 

To test this, I wrote the following JUnit test:

 public class TestConversions { @Test public void testConversions() { String floatValue = Conversions.hexadecimalToFloatingPoint("40000000"); Assert.assertEquals(floatValue, "2.0"); floatValue = Conversions.hexadecimalToFloatingPoint("50000000"); Assert.assertEquals(floatValue, "8589934592"); floatValue = Conversions.hexadecimalToFloatingPoint("C0000000"); Assert.assertEquals(floatValue, "-2.0"); } } 

However, the second statement does not hold. According to various online converters, like this one , 50000000 should be converted to 8589934592 , but Java returns 8589934600 .

 org.junit.ComparisonFailure: Expected :8589934600 Actual :8589934592 

What is the correct result now? If Java is incorrect, then how to fix it?

+5
source share
1 answer

You can achieve this by directly passing the float value to the BigDecimal constructor, as shown below. The cause of the problem: Float.toString(value) (Since this method makes an internal call to FloatingDecimal and toJavaFormatString , it seems to make some rounding of values) so there is no need to use Float.toString instead, just pass the actual float value.

  String myString = "50000000"; Long i = Long.parseLong(myString, 16); Float f = Float.intBitsToFloat(i.intValue()); String finalString= new BigDecimal(f).toPlainString(); System.out.println("final value "+finalString); 

So, just change your method as shown below.

 private static String removeScientificNotation(float value) { return new BigDecimal(value).toPlainString(); } 
+5
source

All Articles