Mathieu Gouin
Mathieu Gouin

Reputation: 67

Round int to nearest greater int ending with 0 (C language)

Let's say I have 43, I want to round it to 50

More examples:
41 would be 50
26 would be 30
21 would be 30
57 would be 60

I know there's a round() function, but I think it rounds up with a smaller number if the original number ends with 5 and less...

My code:

int total = nomber1 + nomber2;
int roundedTotal = 0;
int control;

if (total % 10 == 0) {
    control= 0;
} else {
    control = roundedTotal - total ;
}

Don't pay too much attention to the calculations. All I need is to know how I can round up total to the greatest number ending with 0.

Upvotes: 1

Views: 270

Answers (3)

Harshith Rai
Harshith Rai

Reputation: 3066

Here is a solution using plain calculations and an if.

  • Just do a total % 10 to get the difference from the immediately lesser multiple of 10. eg: 22 -> 22 % 10 = 2
  • Subtract it from the number and add 10 to it to get the nearest higher multiple of 10. 22- 2 + 10 = 30.

In case you want even the multiples of 10 to be converted to next highest multiple of 10, just move the calculation out of the if loop.

int c = 2;
int x = 18;
int total = x + c;

if(total % 10 != 0) {
  total = total - (total%10) + 10;
}

else {
}

console.log(total);

Upvotes: 1

Déjà vu
Déjà vu

Reputation: 28850

Using integers,

total = ((total + 10) / 10) * 10;

For instance 40 would give 50. If 40 should remain 40

total = ((total + 9) / 10) * 10;

Upvotes: 3

chux
chux

Reputation: 154592

Round int to nearest greater int ending with 0

All I need is to know how I can round up total to the greatest number ending with 0.

OP's code is close.

int round_greater_int0(int x) {
  int least_decimal_digit = x%10;  //  -10 < least_decimal_digit < +10
  if (least_decimal_digit >= 0) {
    return x - least_decimal_digit + 10;  // may overflow
  }
  return x - least_decimal_digit;
}

round_greater_int0(40) --> 50. This is what OP is asking for, yet I suspect this is not what OP wants.


double round(double) is a function for floating point math, best not use with an integer problem. Many subtle issues.

Upvotes: 1

Related Questions