DecimalFormat rounding

后端 未结 2 903
庸人自扰
庸人自扰 2020-12-10 01:30

Here is small code to illustrate what I am seeing

float floater = 59.999f;

DecimalFormat df = new DecimalFormat(\"00.0\");

System.out.println(df.format(flo         


        
相关标签:
2条回答
  • 2020-12-10 01:59

    Add this line before using the DecimalFormat:

    df.setRoundingMode(RoundingMode.DOWN);
    

    Take a look at the other rounding modes and see which one is best for you.

    Note : this method works only in JDK 1.6 or above

    0 讨论(0)
  • 2020-12-10 02:00
    float d = 59.999f;
    BigDecimal bd = new BigDecimal(d);
    // Use the returned value from setScale, as it doesn't modify the caller.
    bd = bd.setScale(1, BigDecimal.ROUND_FLOOR);
    String formatted = bd.toString();
    
    0 讨论(0)
提交回复
热议问题