DecimalFormat rounding

2020-02-05 05:51发布

问题:

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

This prints:

60.0

I would like it to print

59.9

What do I need to do?

回答1:

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



回答2:

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