PcAF
PcAF

Reputation: 2007

How to round BigDecimal smaller than 1

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

Answers (5)

DongHoon  Kim
DongHoon Kim

Reputation: 386

System.out.println(Math.round(b.doubleValue()));

Upvotes: 0

CoderNeji
CoderNeji

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

Rafiq
Rafiq

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

Karthigeyan Vellasamy
Karthigeyan Vellasamy

Reputation: 2066

Something like :

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

Upvotes: 1

ThreeSidedCoin
ThreeSidedCoin

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

Related Questions