4

为什么下面的代码:

System.out.println((int)(19.99 * 100));

产生结果“1998”?

4

6 回答 6

9

舍入错误。如果您在没有演员表的情况下查看计算结果,您会得到:

1998.9999999999998

So when you cast to int, the decimal part is dropped, not rounded up, and you get 1998.

The moral is, if you need an exact answer, don't use float / double at all. If you're talking about a discrete value like money, use int and deal with the atomic unit (eg. pence.) If you do need exact decimals, then BigDecimal is your friend.

While you can bodge the result here using Math.round() to bring the result to where it's expected, this won't work in all cases and fails to address the underlying issue.

于 2012-08-06T11:51:42.933 回答
5

这是因为 19.99 无法准确表示。

System.out.println(new BigDecimal(19.99));

打印 this 实际表示的值,该值最接近它可以表示的 19.99。

19.989999999999998436805981327779591083526611328125

并且19.99 * 100

System.out.println(new BigDecimal(19.99 * 100));

这是

1998.999999999999772626324556767940521240234375

问题是您在 19.99 中有一个表示错误,当乘以 100 时仍然存在,您会得到一个稍微太小的数字。

如果你乘以 100 并向下取整(int)那么你应该期望得到 1998 年。

另一种选择是

System.out.println(Math.round(19.99 * 100));
于 2012-08-06T11:50:23.177 回答
1

因为 19.99 * 100 的计算将导致 1998.999999 并且您将其转换为 int 它将丢弃它的小数部分。

于 2012-08-06T11:51:32.950 回答
1

It is due to a rounding issues. double and float are prone to these issues, which is why it is recommended you use the BigDecimal class.

This code should print what is expected:

BigDecimal bg = new BigDecimal("19.99");
System.out.println(bg.multiply(new BigDecimal("10")));

This yields:

199.90

于 2012-08-06T11:52:09.937 回答
1
System.out.println((19.99 * 100));

produces the result 1998.9999999999998 by adding int casting it truncates the fraction part and returns 1998

于 2012-08-06T11:52:47.757 回答
1

Floating point data types (float and double in Java) can only approximately represent most decimal values. See Joshua Bloch's words of wisdom on the subject for more details.

于 2012-08-06T11:53:41.967 回答