如何在c#中为数字字符串添加千位分隔符?

joh*_*eur 3 c# format tostring string-formatting number-formatting

我希望这个"123456789"到这个"123,456,789".

关于如何使用.Format()和数字格式化非字符串类型的大量SO答案.ToString().无法找到有关如何从数字字符串中获取的任何答案.

我可以这样做,但它并不理想:

Convert.ToInt32(minPrice).ToString("N0");
Run Code Online (Sandbox Code Playgroud)

ale*_*chr 9

只需将您认为不理想的功能封装到扩展方法中.

public static string ToFormattedThousands(this string number)
{
    return Convert.ToInt32(number).ToString("N0");
}
Run Code Online (Sandbox Code Playgroud)

只需将此函数放入静态类中,然后您就可以在任何字符串上调用它.

例如 :

string myString = "123456789".ToFormattedThousands();
Run Code Online (Sandbox Code Playgroud)