Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a custom thousand separator in C#

I'm trying not to use the ',' char as a thousand separator when displaying a string, but to use a space instead. I guess I need to define a custom culture, but I don't seem to get it right. Any pointers?

eg: display 1000000 as 1 000 000 instead of 1,000,000

(no, String.Replace() is not the solution I'd like to use :P)

like image 717
Luk Avatar asked Apr 15 '09 15:04

Luk


People also ask

How do I format a thousand separator?

Select the cells that you want to format. On the Home tab, click the Dialog Box Launcher next to Number. On the Number tab, in the Category list, click Number. To display or hide the thousands separator, select or clear the Use 1000 Separator (,) check box.

How do you print a number with commas as thousands separators in Javascript?

The format() method of this object can be used to return a string of the number in the specified locale and formatting options. This will format the number with commas at the thousands of places and return a string with the formatted number.

What is separator in C Plus Plus?

The following characters are used as punctuators (also known as separators) in C++ : [ ] ( ) { } , ; : * ... = # Let's discuss all the above separators one by one : Brackets [ ] - Opening and closing brackets indicate single and multidimensional array subscripts.


2 Answers

I suggest you find a NumberFormatInfo which most closely matches what you want (i.e. it's right apart from the thousands separator), call Clone() on it and then set the NumberGroupSeparator property. (If you're going to format the numbers using currency formats, you need to change CurrencyGroupSeparator instead/as well.) Use that as the format info for your calls to string.Format etc, and you should be fine. For example:

using System; using System.Globalization;  class Test {     static void Main()     {         NumberFormatInfo nfi = (NumberFormatInfo)             CultureInfo.InvariantCulture.NumberFormat.Clone();         nfi.NumberGroupSeparator = " ";          Console.WriteLine(12345.ToString("n", nfi)); // 12 345.00     } } 
like image 110
Jon Skeet Avatar answered Sep 20 '22 22:09

Jon Skeet


Create your own NumberFormatInfo (derivative) with a different thousand separator.

like image 30
Lucero Avatar answered Sep 21 '22 22:09

Lucero