Reputation: 2007
I want to round decimal number to 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 output
3
1
Real output
3
0.5
The problem is that number 0.5 is rounded to 0.5 instead of 1 How to Round BigDecimal smaller than 1
Upvotes: 4
Views: 923
Reputation: 2074
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 output as 3 and 1
...
Upvotes: 2
Reputation: 750
You can use below code to round BigDecimal smaller 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));
Upvotes: 1
Reputation: 2066
Something like :
BigDecimal intvalue= new BigDecimal("0.5");
intvalue = intvalue.setScale(0, RoundingMode.HALF_UP);
Upvotes: 1
Reputation: 119
BigDecimal b=new BigDecimal("0.5");
b = b.setScale(0,BigDecimal.ROUND_HALF_UP);
System.out.println(b.round(MathContext.DECIMAL32));
Upvotes: 1