Reputation: 1039
I need to get these results using BigDecimal roundingmode.xxx and setScale(2) :
(5.789).setScale(2, RoundingMode.xxx) = 5.79
(2.894).setScale(2, RoundingMode.xxx) = 2.89
(2.895).setScale(2, RoundingMode.xxx) = 2.89
Where RoundingMode.xxx has to be same for the three given values.
Ive tried all combinations but with no success and Microsoft Excel set the three results with success.
Upvotes: 3
Views: 4954
Reputation: 1039
The problem is when I was multiplying two BigDecimal
numbers I got a big result. After that I used setScale(2, HalfDown)
but did not get the desired result.
The wrong result
"2.89500004313886165618896484375".setScale(2, BigDecimal.ROUND_HALF_DOWN);
I need 2.89 and the wrong result was 2.90
Using .round(new MathContext(2))
I got it :
"2.89500004313886165618896484375".round(new MathContext(2));
The right result is 2.89
Upvotes: 0
Reputation: 123448
You could use ROUND_HALF_DOWN
:
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. Behaves as for ROUND_UP if the discarded fraction is > 0.5; otherwise, behaves as for ROUND_DOWN.
For your input:
static void roundTo(BigDecimal input)
{
BigDecimal output = input.setScale(2, BigDecimal.ROUND_HALF_DOWN);
System.out.println(input + " => " + output);
}
roundTo(new BigDecimal("5.789"));
roundTo(new BigDecimal("2.894"));
roundTo(new BigDecimal("2.895"));
This would produce:
5.789 => 5.79
2.894 => 2.89
2.895 => 2.89
EDIT: As per your comments, the following might work for you:
BigDecimal output = input.setScale(3, BigDecimal.ROUND_HALF_DOWN).setScale(2, BigDecimal.ROUND_HALF_DOWN);
Upvotes: 4
Reputation: 14413
You are looking for RoundingMode.HALF_DOWN
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. Behaves as for RoundingMode.UP if the discarded fraction is > 0.5; otherwise, behaves as for RoundingMode.DOWN.
Example:
public static void main(String args []){
System.out.println(new BigDecimal("5.789").setScale(2, RoundingMode.HALF_DOWN));
System.out.println(new BigDecimal("2.894").setScale(2, RoundingMode.HALF_DOWN));
System.out.println(new BigDecimal("2.895").setScale(2, RoundingMode.HALF_DOWN));
}
Output
5.79
2.89
2.89
Upvotes: 1