Split number into hundreds tens and units using C#

前端 未结 5 1027
星月不相逢
星月不相逢 2021-01-03 13:00

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

相关标签:
5条回答
  • 2021-01-03 13:02

    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
    
    0 讨论(0)
  • 2021-01-03 13:05
    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)

    0 讨论(0)
  • 2021-01-03 13:12

    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
    
    0 讨论(0)
  • 2021-01-03 13:14

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

    0 讨论(0)
  • 2021-01-03 13:14

    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')));
    
    0 讨论(0)
提交回复
热议问题