nemo_87
nemo_87

Reputation: 4791

Split number into hundreds tens and units using C#

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?

Upvotes: 4

Views: 14455

Answers (5)

Andrey Korneyev
Andrey Korneyev

Reputation: 26876

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

Upvotes: 11

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

Linq implementation:

  String source = "43928";
  // "40000 + 30000 + 900 + 20 + 8"
  String result = String.Join(" + ", source
    .Select((item, index) => item.ToString().PadRight(source.Length - index, '0')));

Upvotes: 4

TarasB
TarasB

Reputation: 2428

The way with the parsing:

var myBigNumber = 43928.ToString();
var asCharachters = myBigNumber.ToArray();
for (var i = 0; i < asCharachters.Length; i++)
{
    var numberOfZeros = asCharachters.Length - i;
    var itemAsString = (asCharachters[i]).ToString().PadRight(numberOfZeros, '0');
    Console.WriteLine( Int32.Parse(itemAsString));
}

Outputs this:

40000
3000
900
20
8

Upvotes: 2

Dario Griffo
Dario Griffo

Reputation: 4274

var x = "4328";
for (int i = 0; i < x.Length; ++i)
{
    var a = x.Substring(x.Length - i - 1, 1).PadRight(i+1, '0');
    Console.WriteLine(a);
}

if you need numbers use int.Parse(a)

Upvotes: 2

ionutioio
ionutioio

Reputation: 238

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

Upvotes: 4

Related Questions