【问题标题】:Truncate Float value up to two decimal point in java在java中将浮点值截断到小数点后两位
【发布时间】: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 位有效数字的精度。如果x5678.1234,您确实会看到5678.12 打印出来。如果您需要超过 8 位左右的有效数字精度,则应使用 double
  • @LuudvanKeulen 要证明它是错误的,请参阅here

标签: java floating-point precision


【解决方案1】:

使用Double而不是Float,否则会丢失精度

DecimalFormat hisFormat = new DecimalFormat("######.##");
hisFormat.setRoundingMode(RoundingMode.DOWN);
Double x = 12345678.12345;
System.out.println("Float Value " + hisFormat.format(x));

使用Float结果为12345678

使用Double结果为12345678.12

【讨论】:

  • 根据我的要求,我将只获得 Float 值。
猜你喜欢
  • 2019-03-01
  • 1970-01-01
  • 2015-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多