【问题标题】:Issue in Decimal Points小数点问题
【发布时间】:2017-08-13 17:48:29
【问题描述】:

我遇到小数点问题我只想得到两个小数点,所以我在下面的代码中使用了这个

 public class TestDateExample1 {
  public static void main(String[] argv){
      double d = 2.34568;
         DecimalFormat f = new DecimalFormat("##.00");
         System.out.println(f.format(d));
    }
  }

当我运行此代码时,输​​出为 2.35,但当小数点高于“5”时我不需要任何增量,我需要精确的小数点,如 2.34。

【问题讨论】:

标签: java rounding decimalformat


【解决方案1】:

您可以使用DecimalFormat#setRoundingMode 来控制舍入的完成方式,并指定您始终要向下舍入(截断):

DecimalFormat f = new DecimalFormat("##.00");
f.setRoundingMode(RoundingMode.DOWN);
System.out.println(f.format(d));

【讨论】:

    【解决方案2】:

    DecimalFormat.setRoundingMode()需要设置为RoundingMode.FLOOR

    【讨论】:

    • 正如@Mureinik 提到的,最好使用RoundingMode.DOWN 来支持双精度为负的情况。也就是说,除非 OP 打算在数字为负数的情况下朝相反方向四舍五入;)
    猜你喜欢
    • 2010-09-22
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 2016-12-03
    • 1970-01-01
    相关资源
    最近更新 更多