我想将数字分成几百个而不是数千个

时间:2018-07-20 06:13:55

标签: c# .net

在对整数(例如1234567890)进行格式化时,我希望使用大小为2(数百个)而不是大小为3(数千个)的组。我已经尝试过这样的事情

int number = 1234567890;
string value = string.Format("{0:#,###0}", number); 

所需的value

12,34,56,78,90

实际的value

1,234,567,890                          

2 个答案:

答案 0 :(得分:0)

尝试一下:-

            static void Main(string[] args)
            {           
            NumberFormatInfo nfi = new CultureInfo("en-US").NumberFormat;

            // Displays a value with the default separator (".").
            Int64 myInt = 123456789012345;
            Console.WriteLine(myInt.ToString("N", nfi));

            // Displays the same value with different groupings.
            int[] mySizes1 = { 2, 3, 4 };
            int[] mySizes2 = { 2, 2 };
            nfi.NumberGroupSizes = mySizes1;
            Console.WriteLine(myInt.ToString("N", nfi));
            nfi.NumberGroupSizes = mySizes2;
            Console.WriteLine(myInt.ToString("N", nfi));
            ReadLine();
            }

有关更多信息,请参见此链接:-https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numbergroupsizes(v=vs.110).aspx

答案 1 :(得分:0)

执行此操作可能有很多逻辑。我发现了一个。 我假设你有字符串。

static void Main(string[] args)
{
    string numbers = "1234567890";

    Console.WriteLine(string.Join(",", CustomSplit(numbers, 1)));
    Console.WriteLine(string.Join(",", CustomSplit(numbers, 2)));
    Console.WriteLine(string.Join(",", CustomSplit(numbers, 3)));

    Console.ReadLine();
}

public static List<string> CustomSplit(string Input, int Length)
{
    List<string> result = new List<string>();


    string[] split = new string[Input.Length / Length + (Input.Length % Length == 0 ? 0 : 1)];

    for (int i = 0; i < split.Length; i++)
    {
    result.Add( Input.Substring(i * Length, i * Length + Length > Input.Length ? 1 : Length));
    }

    return result;
}

输出

1,2,3,4,5,6,7,8,9,0
12,34,56,78,90
123,456,789,0