简体   繁体   中英

Round double with .5 and above to the ceil value

I'm having some issues with rounding up values to intergers. In my app I have this values 250/6=41.6667 . and or this i get the value of 41 instead of 42. Can anyone tell me how can I round up this value to the ceiling?

Here is what I do now:

 public BigDecimal roundToHalf(double d) {
            BigDecimal value = new BigDecimal(d);
            value = value.setScale(0, RoundingMode.HALF_DOWN);
            Log.d(TAG, "youcan val =" + value);
            return value;
    }
/////////
    int nowYouPay = 250;
    int billSize= billTotals.size();// value of 6

    int res =roundToHalf(nowYouPay / billSize);//this retunrs 41

你应该使用int res = Math.round(((float)nowYouPay)/billSize)

Integer division: result is already "rounded down" when you divide nowYouPay / billSize. So you are actually calling roundToHalf(41) instead of roundToHalf(41.666..).

If you don't want the result of division to be 41, you have to use division with at least one floating point argument:

((double) nowYouPay)/ billSize  // 41.6666...
nowYouPay / ((double) billSize) // 41.6666...
250.0 / 6                       // 41.6666...
250 / 6.0                       // 41.6666...
250.0 / 6.0                     // 41.6666...
250 / 6                         // 41

Try this

 public static double roundToHalf(double d) {
         return Math.ceil(d);
 }

or use this:

 public static double roundToHalf(double d) {
         return Math.round(d);
 }

Is more appropriate, approximates your integer 41.6667 to 42 , that is, with values ​​higher than 0.50 higher integer , otherwise the lowest

with input 41.6667 result:

42.0

check this: Math Ceil

and Math Round

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