I have some simple code to round up and round down, but it is producing some unexpected results.
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
double a = 46.66;
System.out.println("Roundup: " + roundUp(a,2) + "\nRound Down: " + roundDown(a,2));
}
public static double roundUp(double a, int scale)
{
BigDecimal value = new BigDecimal(a);
value = value.setScale(scale, RoundingMode.UP);
return value.doubleValue();
}
public static double roundDown(double a, int scale)
{
BigDecimal value = new BigDecimal(a);
value = value.setScale(scale, RoundingMode.DOWN);
return value.doubleValue();
}
When I use 3 digits after decimal, it is working as expected. If a = 44.661, the output is as expected as below.
Roundup: 46.67 Round Down: 46.66
When a=44.66, the round down value reduces by 1 which is unexpected as below.
Roundup: 46.66 Round Down: 46.65
How do I get 44.66 for round down and 44.67 for roundUp while still retaining the above results.
Thanks in advance for your help
That's because you're not really using BigDecimals, you're using doubles. When you type 44.66 it gets converted to a double, which results in a value slightly less than 44.66. BigDecimal can't fix rounding errors that have already occurred before you give it the input.
Try this instead.
public static void main(String[] args) throws Exception {
BigDecimal a = new BigDecimal("46.66");
System.out.println("Roundup: " + roundUp(a,2) + "\nRound Down: " + roundDown(a,2));
}
public static BigDecimal roundUp(BigDecimal a, int scale)
{
return a.setScale(scale, RoundingMode.UP);
}
public static BigDecimal roundDown(BigDecimal a, int scale)
{
return a.setScale(scale, RoundingMode.DOWN);
}
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