Java BigDecimal: Round to the nearest whole value
If i go by Grodriguez's answer
System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);
This is the output
100.23 -> 100
100.77 -> 101
Which isn't quite what i want, so i ended up doing this..
System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);
This is what i get
100.23 -> 100.00
100.77 -> 101.00
This solves my problem for now .. : ) Thank you all.
You can use setScale()
to reduce the number of fractional digits to zero. Assuming value
holds the value to be rounded:
BigDecimal scaled = value.setScale(0, RoundingMode.HALF_UP);
System.out.println(value + " -> " + scaled);
Using round()
is a bit more involved as it requires you to specify the number of digits to be retained. In your examples this would be 3, but this is not valid for all values:
BigDecimal rounded = value.round(new MathContext(3, RoundingMode.HALF_UP));
System.out.println(value + " -> " + rounded);
(Note that BigDecimal
objects are immutable; both setScale
and round
will return a new object.)