Formatting a double and not rounding off

前端 未结 5 1698
旧时难觅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: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
    

提交回复
热议问题