【发布时间】:2017-07-04 18:59:33
【问题描述】:
DecimalFormat hisFormat = new DecimalFormat("########.##");
hisFormat.setRoundingMode(RoundingMode.DOWN);
Float x=12345678.12345f;
System.out.println("Float Value " + hisFormat.format(x));
上面的代码打印“浮点值”为 12345678 我需要12345678.12
我怎样才能得到我的结果?请告诉我。
【问题讨论】:
-
将你的数字乘以 100。四舍五入。除以 100,然后打印。
-
@LuudvanKeulen 那是wrong way to do it。
-
@LuudvanKeulen 浮点数存储在 base-2 中,而不是 base-10 中,因此乘法会引入舍入误差,这通常会产生不正确的结果。
-
这不是真正的重复。该值打印为
12345678的原因是floats 不能保持13 位有效数字的精度。如果x是5678.1234,您确实会看到5678.12打印出来。如果您需要超过 8 位左右的有效数字精度,则应使用double。 -
@LuudvanKeulen 要证明它是错误的,请参阅here。
标签: java floating-point precision