简体   繁体   中英

Java BigDecimal Rounding up to two decimal places

I am trying to round off BigDecimal in Java below is the code that I executed

   BigDecimal prec1 = new BigDecimal("49.3249999999999999990")
                             .setScale( 2, RoundingMode.HALF_UP);
   BigDecimal prec2 = new BigDecimal("49.3249999999999999990")
                             .setScale( 3, RoundingMode.HALF_UP)
                             .setScale(2, RoundingMode.HALF_UP);

So the output are prec1 = 49.32 and prec2 = 49.33 for my use case I need always to round off to 49.33 so is there any other way to round off to 49.33 other than setting scale two times? also I am using the HALF_UP for all the computations, I can't got for CEILING or UP, I have to follow the rule for half up (eg: round off to 1 if value is greater than or equal.5 ) So following this rule is there any way to achieve the mentioned result?

Try the following code. It is rounding half-up as expected as normally defined. That is such that 0.49999999999999990<0.5 so rounds down because it rounds down below 0.5 (a half).

I believe the OP has misunderstood the rule and just needs to use the ordinary HALF_UP rounding mode.

public static void main (String[] args) throws java.lang.Exception
{
    
    BigDecimal value=new BigDecimal("49.3249999999999999990");
    BigDecimal mark=new BigDecimal("49.325");//Values less than this round down!
    BigDecimal down=new BigDecimal("49.32");
    boolean expectDown;
    
    if(value.compareTo(mark)<0){
        System.out.println(value + " is less than "+mark);
        System.out.println("So rounds down");
        expectDown=true;
    }else{
        System.out.println(value + " is greater than or equal to "+mark);
        System.out.println("So rounds up");
        expectDown=false;
    }
    BigDecimal result=value.setScale(2,RoundingMode.HALF_UP);
    System.out.println("Rounded to "+result);
    if(result.equals(down)==expectDown){
        System.out.println("As expected");  
    }else{
        System.out.println("NOT As expected!!!");
    }
}

Expected Output:

49.3249999999999999990 is less than 49.325
So rounds down
Rounded to 49.32
As expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM