开发者

DecimalFormat rounding

开发者 https://www.devze.com 2023-03-14 15:27 出处:网络
Here is small code to illustrate what I am seeing float floater = 59.999f; DecimalFormat df = new DecimalFormat(\"00.0\");

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 t开发者_如何学编程o print

59.9

What do I need to do?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消