如何将字符串格式化为带有货币符号和分隔符的字符串

How to format a string into a string with currency symbol and seperators

int、double、decimal 的数字格式可以通过使用标准数字格式化程序简单地实现,例如假设 Culture 是“en-GB”:

int value = 1000;
Console.WriteLine(value.ToString("C0")); // Would output £1,000

但是我想知道是否有一种简单的方法可以将字符串格式化为与上述相同的效果。例如:

string amount = "£2000"; // Would want to format to "£2,000"

有没有办法格式化这个字符串,以便在正确的位置添加千位分隔符?

鉴于它是一个字符串,我认为如果不事先将字符串转换为数字数据类型,数字格式将无法工作:

var result = Int32.Parse("£2000", NumberStyles.AllowCurrencySymbol, new CultureInfo("en-GB"));
Console.WriteLine(result.ToString("C0", new CultureInfo("en-GB"))); // Outputs £2,000

然而,将字符串转换为 int 然后再转换回字符串有点冗长。如果起始字符串具有货币符号,是否有更简单的方法来执行此操作?

Given it's a string I don't think numerical formatting would work without converting the string to a numerical data type beforehand

确实如此。

Is there is a simpler way to do this given that the starting string has the currency symbol?

没有。而且我严重怀疑这样的功能是否会添加 and/or 受到开发者社区的欢迎。此类功能的正式规范将是一场复杂的噩梦。

当然,在您的特定情况下,如果您确定您的字符串始终由“货币符号 + 不带逗号或句点的数字序列”组成,您可以开发一个string-based 针对您的用例优化的解决方案(例如,)。但是,我认为您当前的解决方案既可读又可维护,并且您可以通过保持这种方式来帮助您未来的自己。如果你多次需要它,把它提取到一个方法中。