1

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?

User7007
  • 331
  • 3
  • 14
  • 2
    I don't think there's a simpler way - you can't format an arbitrary string as a number, you need to parse it first. – Charles Mager Apr 06 '22 at 16:07
  • 1
    One thing to understand about this is, thanks to internationalization/cultural issues, converting between strings and numbers is far more complicated than you would possibly believe. It's _slow_, it's _error prone_, and it's a significant source of software bugs, and therefore something to avoid as much as possible. Therefore the best process always leans as much as possible on tools provided by your platform (like `int.Parse()` and `int.ToString()`), as well as keeping number values as number types for as long as possible, only converting to string when absolutely necessary. – Joel Coehoorn Apr 06 '22 at 17:10

1 Answers1

3

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.

Heinzi
  • 167,459
  • 57
  • 363
  • 519