有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java格式化双精度且不舍入

我需要将double的格式(而不是四舍五入)设置为小数点后2位

我试过:

String s1 = "10.126";
Double f1 = Double.parseDouble(s1);
DecimalFormat df = new DecimalFormat(".00");
System.out.println("f1"+df.format(f1));

结果:

10.13

但是我要求输出为10.12


共 (5) 个答案

  1. # 1 楼答案

    您可以将格式化程序的舍入模式设置为“向下”:

    df.setRoundingMode(RoundingMode.DOWN);
    
  2. # 2 楼答案

    如果你想做的是在两个小数点截断一个字符串,考虑只使用如下所示的字符串函数:

    String s1 = "10.1234";
    String formatted = s1;
    int numDecimalPlaces = 2;
    int i = s1.indexOf('.');
    if (i != -1 && s1.length() > i + numDecimalPlaces) {
        formatted = s1.substring(0, i + numDecimalPlaces + 1);
    }
    System.out.println("f1" + formatted);
    

    这将节省解析为Double,然后格式化为字符串的时间

  3. # 3 楼答案

    为什么不使用BigDecimal

    BigDecimal a = new BigDecimal("10.126");
    BigDecimal floored = a.setScale(2, BigDecimal.ROUND_DOWN);  //  == 10.12
    
  4. # 4 楼答案

    你试过了吗

    String s1 = "10.126";
    Double f1 = Double.parseDouble(s1);
    DecimalFormat df = new DecimalFormat(".00");
    df.setRoundingMode(RoundingMode.FLOOR);
    
    System.out.println("f1"+df.format(f1));
    
  5. # 5 楼答案

    调用^{}以适当地设置^{}

    String s1 = "10.126";
    Double f1 = Double.parseDouble(s1);
    DecimalFormat df = new DecimalFormat(".00");
    df.setRoundingMode(RoundingMode.DOWN); // Note this extra step
    System.out.println(df.format(f1));
    

    输出

    10.12