Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading