How to round BigDecimal less than 1

I want to round a decimal number to the nearest natural number. Example:

public static void main(String[] arguments){ BigDecimal a=new BigDecimal("2.5"); BigDecimal b=new BigDecimal("0.5"); System.out.println(a.round(new MathContext(1,RoundingMode.UP))); System.out.println(b.round(new MathContext(1,RoundingMode.UP))); } 

Expected Result

 3 1 

Real output

 3 0.5 

The problem is that the number 0.5 is rounded to 0.5 instead of 1. How to round BigDecimal to less than 1

+4
source share
5 answers

Sort of:

  BigDecimal intvalue= new BigDecimal("0.5"); intvalue = intvalue.setScale(0, RoundingMode.HALF_UP); 
+1
source

This will do what you want ...

 BigDecimal a=new BigDecimal("2.5"); BigDecimal b=new BigDecimal("0.5"); System.out.println(Math.round(a.doubleValue())); System.out.println(Math.round(b.doubleValue())); 

This will give you a result like 3 and 1 ...

+2
source
 BigDecimal b=new BigDecimal("0.5"); b = b.setScale(0,BigDecimal.ROUND_HALF_UP); System.out.println(b.round(MathContext.DECIMAL32)); 
+1
source

You can use below code to round BigDecimal to less than 1.

  BigDecimal a = new BigDecimal("2.5"); BigDecimal b = new BigDecimal("0.5"); System.out.println(a.setScale(0, RoundingMode.UP)); System.out.println(b.setScale(0, RoundingMode.UP)); 
+1
source
 System.out.println(Math.round(b.doubleValue())); 
0
source

All Articles