Split number into hundreds tens and units using C#

2020-03-07 04:34发布

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?

5条回答
Luminary・发光体
2楼-- · 2020-03-07 04:50
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)

查看更多
神经病院院长
3楼-- · 2020-03-07 04:55

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

查看更多
贪生不怕死
4楼-- · 2020-03-07 05:00

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
查看更多
欢心
5楼-- · 2020-03-07 05:07

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')));
查看更多
我想做一个坏孩纸
6楼-- · 2020-03-07 05:12

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
查看更多
登录 后发表回答