2

I have to write a program at school that allows the user to input a 7-digits of a GTIN-8 barcode and calculate check digit. To calculate the check digit the seven input numbers are multiplied by 3, 1, 3, 1 etc.

for (i = 0; i < 7; i++)
{
    //Convert String to Character
    ch = gtinNum[i];

    //Convert Character to Integer
    number = Convert.ToInt32(ch);
    product = number * weights[i];
    total = total + product;
}//end for loop

After that, the total is taken away from the nearest higher ten. For example if the total was 43 then it would be 50-43. In the simplest way possible, how do I round up to the higher ten?

Siyavash Hamdi
  • 2,764
  • 2
  • 21
  • 32
  • 3
    How about using modulus to get the value down to between 0 and 10 to begin with, and simply subtract it from 10? `10 - (total % 10)` ? – Lasse V. Karlsen May 31 '16 at 11:36
  • You can actually look at what it actually _means_ to subtract from the next highest multiple of ten. And then look whether there's a built-in operator to do the same. – Joey May 31 '16 at 11:36
  • Using pure `int` math it's `total / 10 * 10 + 10`. – Sinatr May 31 '16 at 12:50

1 Answers1

4

You can use Math.Ceiling, you just need to divide by ten first and multiply by 10 afterwards. Divide by 10.0 to avoid integer division(Math.Ceiling takes double):

int num = 43;
int nextHigherTen = (int)Math.Ceiling(num / 10.0) * 10;

This "rounds" 41-50 up to 50. If you want it from 40-49 you could use this:

int nextHigherTen = (int)Math.Ceiling((num + 1) / 10.0) * 10;
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939