java - Rounding Bigdecimal values with 2 Decimal Places -
i want function convert bigdecimal 10.12 10.12345
, 10.13 10.12556
. no function satisfying both conversion in same time.please achieve this.
below tried.
bigdecimal = new bigdecimal("10.12345"); a.setscale(2, bigdecimal.round_up) a.setscale(2, bigdecimal.round_ceiling) a.setscale(2, bigdecimal.round_down) a.setscale(2, bigdecimal.round_floor) a.setscale(2, bigdecimal.round_half_down) a.setscale(2, bigdecimal.round_half_even) a.setscale(2, bigdecimal.round_half_up)
output :
10.12345::10.13 10.12345::10.13 10.12345::10.12 10.12345::10.12 10.12345::10.12 10.12345::10.12 10.12345::10.12 bigdecimal b = new bigdecimal("10.12556"); b.setscale(2, bigdecimal.round_up) b.setscale(2, bigdecimal.round_ceiling) b.setscale(2, bigdecimal.round_down) b.setscale(2, bigdecimal.round_floor) b.setscale(2, bigdecimal.round_half_down) b.setscale(2, bigdecimal.round_half_even) b.setscale(2, bigdecimal.round_half_up)
output :
10.12556::10.13 10.12556::10.13 10.12556::10.12 10.12556::10.12 10.12556::10.12 10.12556::10.12 10.12556::10.12
i think roundingmode
looking round_half_even
. the javadoc:
rounding mode round towards "nearest neighbor" unless both neighbors equidistant, in case, round towards neighbor. behaves round_half_up if digit left of discarded fraction odd; behaves round_half_down if it's even. note rounding mode minimizes cumulative error when applied repeatedly on sequence of calculations.
here quick test case:
bigdecimal = new bigdecimal("10.12345"); bigdecimal b = new bigdecimal("10.12556"); = a.setscale(2, bigdecimal.round_half_even); b = b.setscale(2, bigdecimal.round_half_even); system.out.println(a); system.out.println(b);
correctly prints:
10.12 10.13
Comments
Post a Comment