Formatting Numbers In C#: Add That Appostrophe In There

In case you’ve been wondering how you could place an apostrophe for every three digits of a number (e.g. 1'337 or 1'234'567) in C# using ToString(string format), you can achieve this with the following code:

int nr = 1337;
nr.ToString("#,#0");

This code snippet will format the number to 1'337, and if nr == 0 it will print 0; if you omit the 0 in #,#0, it will just print a whitespace in the case of nr == 0.

I know, it’s not the most interesting piece of code, but nonetheless it took me some time until I figured this one out. And yes, my first attempt looked something like nr.ToString("#'#0").

I hope I’ll save somebody some precious time with this post.

Write a Comment