Numerical formatting of int, double, decimal can be simply achieved via using Standard Numerical Formatter for example assuming Culture is "en-GB":
int value = 1000;
Console.WriteLine(value.ToString("C0")); // Would output £1,000
However I am wondering if there is a simple way to format a string to something of the same effect as above. For example:
string amount = "£2000"; // Would want to format to "£2,000"
Is there a way to format this string so that the thousands separator is added in the correct position?
Given it's a string I don't think numerical formatting would work without converting the string to a numerical data type beforehand:
var result = Int32.Parse("£2000", NumberStyles.AllowCurrencySymbol, new CultureInfo("en-GB"));
Console.WriteLine(result.ToString("C0", new CultureInfo("en-GB"))); // Outputs £2,000
However its a bit verbose to convert string to int then back to string. Is there is a simpler way to do this given that the starting string has the currency symbol?
CodePudding user response:
Given it's a string I don't think numerical formatting would work without converting the string to a numerical data type beforehand
Indeed.
Is there is a simpler way to do this given that the starting string has the currency symbol?
No. And I seriously doubt that such a feature would ever be added and/or welcomed by the developer community. A formal specification for such a feature would be a complexity nightmare.
Of course, in your particular case, if you are sure that your string always consists of "currency symbol sequence of digits without comma or period", you could develop a string-based solution optimized for your use case (for example, a fancy regular expression). However, I think that your current solution is both readable and maintainable and you would do your future self a favor by keeping it that way. If you need it multiple times, extract it into a method.