Search code examples
javaprintfdouble

Format Java double with only 2 decimal places without rounding


I have variables that are doubles and I want to get the double with only 2 numbers after the decimal point. I tried it with

System.out.printf("%1.2f", number1); but the decimal places get rounded. For example if I have number1 = 19.867, I just want to get 19.86 and not the rounded version 19.87. How can I do that?


Solution

  • You can use DecimalFormat with an apropriate pattern and a RoundingMode to specify rounding behavior:

    double number1 = 19.867;
    
    DecimalFormat df = new DecimalFormat("#.##");
    df.setRoundingMode(RoundingMode.DOWN);
    
    System.out.println(df.format(number1));
    

    The same can be achieved by converting the double value to BigDecimal and use BigDecimal‘s setScale() method with a RoundingMode

    BigDecimal bigDecimalNumber1 = new BigDecimal(number1).setScale(2, RoundingMode.DOWN);
    System.out.println(bigDecimalNumber1.doubleValue());