Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float round up to 2 decimals java

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
like image 371
wvp Avatar asked Jul 10 '13 17:07

wvp


3 Answers

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.

like image 114
Jonathan Drapeau Avatar answered Sep 30 '22 16:09

Jonathan Drapeau


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.

like image 26
nachokk Avatar answered Sep 30 '22 15:09

nachokk


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)

like image 35
Joachim Isaksson Avatar answered Sep 30 '22 16:09

Joachim Isaksson