formatting string in MVC /C#

后端 未结 10 1936
不知归路
不知归路 2021-02-19 03:15

I have a string 731478718861993983 and I want to get this 73-1478-7188-6199-3983 using C#. How can I format it like this ?

Thanks.

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-19 03:44

    If you're dealing with a long number, you can use a NumberFormatInfo to format it:

    First, define your NumberFormatInfo (you may want additional parameters, these are the basic 3):

    NumberFormatInfo format = new NumberFormatInfo();
    format.NumberGroupSeparator = "-";
    format.NumberGroupSizes = new[] { 4 };
    format.NumberDecimalDigits = 0;        
    

    Next, you can use it on your numbers:

    long number = 731478718861993983;
    string formatted = number.ToString("n", format);
    Console.WriteLine(formatted);
    

    After all, .Net has very good globalization support - you're better served using it!

提交回复
热议问题