【发布时间】:2016-09-13 08:53:57
【问题描述】:
我正在使用以下代码将十六进制 String 转换为浮点 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);
}
为了对此进行测试,我编写了以下JUnit 测试:
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");
}
}
但是,第二个断言失败。根据this one等各种在线转换器,50000000应转换为8589934592,但Java返回8589934600。
org.junit.ComparisonFailure:
Expected :8589934600
Actual :8589934592
现在哪个结果是正确的?如果Java错了,我该如何纠正呢?
【问题讨论】:
-
我怀疑你所看到的是
float应该只依赖 7 位有效数字的精度...(尝试返回float而不是String,并比较你的结果到 8589934600f) -
请注意,最接近 8589934600 的精确浮点值是 8589934592。
-
这就是为什么您不应该与浮点数进行精确比较的原因。对于单元测试中的断言,有
Assert#equals(floatA, floatB, delta)。 -
欺负请找我的答案
标签: java string floating-point bigdecimal data-conversion