Formatting a double and not rounding off

前端 未结 5 1684
旧时难觅i
旧时难觅i 2020-12-18 21:23

I need to format (and not round off) a double to 2 decimal places.

I tried with:

String s1 = \"10.126\";
Double f1 = Double.pa         


        
相关标签:
5条回答
  • 2020-12-18 22:00

    Why not use BigDecimal

    BigDecimal a = new BigDecimal("10.126");
    BigDecimal floored = a.setScale(2, BigDecimal.ROUND_DOWN);  //  == 10.12
    
    0 讨论(0)
  • 2020-12-18 22:02

    Call setRoundingMode to set the RoundingMode appropriately:

    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));
    

    Output

    10.12
    
    0 讨论(0)
  • 2020-12-18 22:11

    Have you tried RoundingMode.FLOOR?

    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));
    
    0 讨论(0)
  • 2020-12-18 22:14

    If all you want to do is truncate a string at two decimal places, consider using just String functions as shown below:

    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);
    

    This saves on parsing into a Double and then formatting back into a String.

    0 讨论(0)
  • 2020-12-18 22:23

    You can set the rounding mode of the formatter to DOWN:

    df.setRoundingMode(RoundingMode.DOWN);
    
    0 讨论(0)
提交回复
热议问题