Round a double to 2 decimal places [duplicate]

2018-12-31 01:25发布

This question already has an answer here:

If the value is 200.3456, it should be formatted to 200.34. If it is 200, then it should be 200.00.

13条回答
美炸的是我
2楼-- · 2018-12-31 01:40
double d = 28786.079999999998;
String str = String.format("%1.2f", d);
d = Double.valueOf(str);
查看更多
忆尘夕之涩
3楼-- · 2018-12-31 01:41

For two rounding digits. Very simple and you are basically updating the variable instead of just display purposes which DecimalFormat does.

x = Math.floor(x * 100) / 100;

查看更多
牵手、夕阳
4楼-- · 2018-12-31 01:44

If you just want to print a double with two digits after the decimal point, use something like this:

double value = 200.3456;
System.out.printf("Value: %.2f", value);

If you want to have the result in a String instead of being printed to the console, use String.format() with the same arguments:

String result = String.format("%.2f", value);

Or use class DecimalFormat:

DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
查看更多
春风洒进眼中
5楼-- · 2018-12-31 01:45

In your question, it seems that you want to avoid rounding the numbers as well? I think .format() will round the numbers using half-up, afaik?
so if you want to round, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest?

You could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.

200.3456 * 100 = 20034.56;  
(int) 20034.56 = 20034;  
20034/100.0 = 200.34;

You might have issues with really really big numbers close to the boundary though. In which case converting to a string and substring'ing it would work just as easily.

查看更多
浅入江南
6楼-- · 2018-12-31 01:47

If you really want the same double, but rounded in the way you want you can use BigDecimal, for example

new BigDecimal(myValue).setScale(2, RoundingMode.HALF_UP).doubleValue();
查看更多
路过你的时光
7楼-- · 2018-12-31 01:50

Rounding a double is usually not what one wants. Instead, use String.format() to represent it in the desired format.

查看更多
登录 后发表回答