value = value.setScale(2, RoundingMode.CEILING)
Answer from Louis Wasserman on Stack OverflowI think that the RoundingMode you are looking for is HALF_EVEN. From the javadoc:
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.
Here is a quick test case:
CopyBigDecimal a = new BigDecimal("10.12345");
BigDecimal b = new BigDecimal("10.12556");
a = a.setScale(2, RoundingMode.HALF_EVEN);
b = b.setScale(2, RoundingMode.HALF_EVEN);
System.out.println(a);
System.out.println(b);
Correctly prints:
Copy10.12
10.13
UPDATE:
setScale(int, int) has not been recommended since Java 1.5, when enums were first introduced, and was finally deprecated in Java 9. You should now use setScale(int, RoundingMode) e.g:
setScale(2, RoundingMode.HALF_EVEN)
Add 0.001 first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)
Code example:
Copypublic static void main(String[] args) {
BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(b);
}
So far I can not come up with a solution, I tried the DecimalFormat class, but it doesn't work.
I have this so far:
double x = 2100.000000;DecimalFormat df = new DecimalFormat("0.00");String formatted = df.format(x);double y = Double.parseDouble(formatted);
BigDecimal is immutable, any operation on it including setScale(2, BigDecimal.ROUND_HALF_UP) produces a new BigDecimal. Correct code should be:
BigDecimal bd = new BigDecimal(1);
bd.setScale(2, BigDecimal.ROUND_HALF_UP); // this does NOT change bd
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(bd);
Output:
1.00
Note:
Since Java 9 BigDecimal.ROUND_HALF_UP has been deprecated and you should now use RoundingMode.HALF_UP.
you can use the round up format
BigDecimal bd = new BigDecimal(2.22222);
System.out.println(bd.setScale(2,BigDecimal.ROUND_UP));
Hope this help you.
Well this one works...
double roundOff = Math.round(a * 100.0) / 100.0;
Output is
123.14
Or as @Rufein said
double roundOff = (double) Math.round(a * 100) / 100;
this will do it for you as well.
double d = 2.34568;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println(f.format(d));