How do I round a double to two decimal places in J

2019-01-03 16:31发布

This is what I did to round a double to 2 decimal places:

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

This works great if the amount = 25.3569 or something like that, but if the amount = 25.00 or the amount = 25.0, then I get 25.0! What I want is both rounding as well as formatting to 2 decimal places.

标签: java double
20条回答
疯言疯语
2楼-- · 2019-01-03 16:46

Use a digit place holder (0), as with '#' trailing/leading zeros show as absent:

DecimalFormat twoDForm = new DecimalFormat("#.00");
查看更多
别忘想泡老子
3楼-- · 2019-01-03 16:49

If you want the result to two decimal places you can do

// assuming you want to round to Infinity.
double tip = (long) (amount * percent + 0.5) / 100.0; 

This result is not precise but Double.toString(double) will correct for this and print one to two decimal places. However as soon as you perform another calculation, you can get a result which will not be implicitly rounded. ;)

查看更多
小情绪 Triste *
4楼-- · 2019-01-03 16:50
做自己的国王
5楼-- · 2019-01-03 16:51
DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);
查看更多
做个烂人
6楼-- · 2019-01-03 16:52

First declare a object of DecimalFormat class. Note the argument inside the DecimalFormat is #.00 which means exactly 2 decimal places of rounding off.

private static DecimalFormat df2 = new DecimalFormat("#.00");

Now, apply the format to your double value:

double input = 32.123456;
System.out.println("double : " + df2.format(input)); // Output: 32.12

Note in case of double input = 32.1;

Then the output would be 32.10 and so on.

查看更多
Melony?
7楼-- · 2019-01-03 16:54

You can use org.apache.commons.math.util.MathUtils from apache common

double round = MathUtils.round(double1, 2, BigDecimal.ROUND_HALF_DOWN);

查看更多
登录 后发表回答