Search code examples
c#splitint

Split an integer


I have been searching around the internet for a while but haven't found what I am looking for.

Let me start with some code example:

int a = 25;

int b;
int c;

What I want to do here is I want to split the a variable and give the two values to variable b and c. The result would be int b = 2 and int c = 5, or vice versa (doesn't matter in the purpose I'm going to use this).

How can you do this?


Solution

  • You can use integer division and modulo for that:

    int b = a / 10;
    int c = a % 10;
    

    If the variable a contains a larger number, you would first determine how many digits you want in each variable. If you for example want two digits in c, you would use 100 as the second operand in both operations.