BigDecimal.setScale方法结果不符合预期:4.780保留两位小数未得4.8
Why Your Rounding Function Returns 4.78 Instead of 4.8
Ah, I see where the confusion is here! Let's break this down step by step to clear things up.
First, let's look at your code snippet:
return new BigDecimal("4.780").setScale(2, RoundingMode.HALF_UP).doubleValue();
Here's what's actually happening:
- The
setScale(2, RoundingMode.HALF_UP)call tells BigDecimal to retain 2 decimal places, using standard "round half up" (四舍五入) logic. - To apply this rounding, it checks the digit immediately after the 2nd decimal place (the 3rd digit) to decide if the 2nd decimal digit needs to be rounded up.
- In your value
4.780, that 3rd decimal digit is0—which is less than 5. So the 2nd decimal digit (8) stays exactly as it is, and we just drop the trailing 0. That's why you end up with4.78instead of your expected4.8.
How to get the 4.8 result you want:
If your goal is to round to 1 decimal place (so 4.780 becomes 4.8), you just need to adjust the first parameter of setScale() to 1:
return new BigDecimal("4.780").setScale(1, RoundingMode.HALF_UP).doubleValue();
With this change, BigDecimal will look at the 2nd decimal digit (8), which is >=5. That triggers rounding up the 1st decimal digit (7 becomes 8), giving you the 4.8 result you were expecting.
Quick recap to avoid future mix-ups:
setScale(n)means "keep n decimal places", and rounding is determined by the (n+1)th digit.- Your original code targeted 2 decimal places, so no rounding up occurred because the 3rd digit was 0. Targeting 1 decimal place activates the rounding behavior you intended.
内容的提问来源于stack exchange,提问作者Yevhen




