Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split number into hundreds tens and units using C#

Tags:

string

c#

split

What is the best way to split some given larger number into hundreds, tens and units in C#?

For example: If I enter number 43928 how can I get 40000 + 3000 + 900 + 20 + 8 on the output?

like image 843
nemo_87 Avatar asked Sep 02 '25 02:09

nemo_87


2 Answers

Something like this:

long x = 43928;
long i = 10;

while (x > i / 10)
{
    Console.WriteLine(x % i - x % (i / 10));
    i *= 10;
}

it will give you output

8
20
900
3000
40000
like image 157
Andrey Korneyev Avatar answered Sep 04 '25 16:09

Andrey Korneyev


You have to use the % operator. Example: 43928 / 10000 = 4; 43928 % 10000 = 3928; 3928 /1000 = 3; 3928 %1000 = 928, etc...

like image 42
ionutioio Avatar answered Sep 04 '25 15:09

ionutioio