2

我有一个函数可以将浮点数从 JNI 本机返回到 Java。这应该是一个简单的调用,但我得到了奇怪的结果。

在我的测试用例中,我将值 1.61863e+010 返回到 java 中。代码很简单:

cout << result << endl;  cout.flush(); // get 1.61863e+010
return (jfloat) result;

(澄清一下,如果 cout.precision(6),我得到 16186300000.000000)

但是我的 Java 代码正在接收 1.61863004E10。当我使用

DecimalFormat formatter = new DecimalFormat("###,###.######");
System.out.println(formatter.format(result));

我得到 16,186,300,416。

这个 416 是从哪里来的?我认为 jfloat 和 float 都是 32 位 IEEE 浮点数,所以不应该有任何精度损失。

非常感谢。

4

2 回答 2

6

You're using a float, which only has 7 decimal digits of precision (23 bits of mantissa, with the implicit bit for normalized numbers). Therefore you should regard anything after that as effectively noise. Your value isn't actually changing - it's just that the displayed representation differs between Java and your C++ implementation.

于 2012-06-20T16:44:43.887 回答
3

它的 C++ 程序很可能四舍五入到 7 位有效数字,即float. 如果您将 Java 中的值四舍五入到 7 位,您将给出相同的数字。当您使用 DecimalFormat 时,默认情况下它将打印最接近的整数。

System.out.println("(float) " + 16186300000.0 + 
                   " is actually " + new BigDecimal((float) 16186300000.0));

印刷

(float) 1.61863E10 is actually 16186300416
于 2012-06-20T16:46:17.767 回答