Truncate a float and a double in java

前端 未结 6 587
后悔当初
后悔当初 2020-12-16 01:33

I want to truncate a float and a double value in java.

Following are my requirements: 1. if i have 12.49688f, it should be printed as 12.49 without rounding off 2

6条回答
  •  余生分开走
    2020-12-16 01:51

    try this out-

    DecimalFormat df = new DecimalFormat("##.##");
    df.setRoundingMode(RoundingMode.DOWN);
    System.out.println(df.format(12.49688f));
    System.out.println(df.format(12.456));
    System.out.println(df.format(12.0));
    

    Here, we are using decimal formatter for formating. The roundmode is set to DOWN, so that it will not auto-round the decimal place.

    The expected result is:

    12.49
    12.45
    12
    

提交回复
热议问题