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 + 2
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
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)
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
You have to use the %
operator. Example:
43928 / 10000 = 4; 43928 % 10000 = 3928; 3928 /1000 = 3; 3928 %1000 = 928, etc...
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')));