I'm trying to round a float up to 2 decimals.
I've 2 float values:
1.985
29.294998
Both of them will need to be rounded up so I end up with the following:
1.99
29.30
When I use the following method:
public static Float precision(int decimalPlace, Float d) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.floatValue();
}
Te result is:
1.99
29.29
Since you are using BigDecimal.ROUND_HALF_UP
, 29.294998
is rounded to 29.29
. You might want to use BigDecimal.ROUND_UP
instead.
Check BigDecimal doc for more informations on each rounding available.
Instead of this
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
Use
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_CEILING);
About ROUND_CEILING
Rounding mode to round towards positive infinity. If the BigDecimal is positive, behaves as for ROUND_UP; if negative, behaves as for ROUND_DOWN. Note that this rounding mode never decreases the calculated value.
You can use DecimalFormat
if you want.
Since you always want to round up, what you want is simply not BigDecimal.ROUND_HALF_UP
but instead BigDecimal.ROUND_UP
or BigDecimal.ROUND_CEILING
.
Use BigDecimal.ROUND_UP
if you want negative numbers to round down (-29.294998 to -29.30).
Use BigDecimal.ROUND_CEILING
if you want negative numbers to round up (-29.294998 to -29.29).
With positive numbers, they will both do the rounding you're trying to do (ie round up)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With