Split number into hundreds tens and units using C#

浪尽此生 提交于 2020-04-06 03:52:07

问题


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?


回答1:


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



回答2:


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




回答3:


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')));



回答4:


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)




回答5:


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


来源:https://stackoverflow.com/questions/26362388/split-number-into-hundreds-tens-and-units-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!