Default Number Format for ToString

Is it possible to determine the default number format, which is used whenever I convert an integer (or double , etc.) to String without specifying a format string?

C # example:

 int i = 123456; string s = "Hello " + i; // or alternatively with string.Format without format definition string s = string.Format("Hello {0}", i); 

RABOR ASP.NET example:

 <div> Hello @i </div> 

I think all of these lines of code implicitly use the default ToString() method for Int32 . And not surprisingly, all of these lines of code lead to "Hello 123456" , but I want "Hello 123,456" .

So, can I indicate that "N0" should be used by default (at least for integer )?

I already found the question Set the default date format in C # format - it looked pretty good, but that doesn't help me for numbers.


Edit: I know that I could write an extension method that I can use throughout the application, but that is not what I am looking for. I would like to find a property (perhaps somewhere hidden in CultureInfo or NumberFormatInfo ) that is currently set to "G" and used by default as Int32.ToString() .

+7
c # number-formatting cultureinfo
source share
5 answers

You can override the toString () methods in your class as follows:

  public override string ToString() { int i = 123456; string s = "Hello " + i; return string.Format("Hello {0}", i); } 
0
source share

you can use extension methods

 public static class MyExtensions { public static string ToDefaultFormatString(this int i) { //Staf } } 

and your code looks like

 int i = 123456; string s = "Hello " + i.ToDefaultFormatString(); 
0
source share

As you try to change functionality for a primitive type that does not have a class, you cannot override the ToString() method.

However, you can create an extension method.

 namespace System { public class IntExt { public string ToStringN0(this int i) { return i.ToString("N0"); } } } 

and then use

 int i = 5000; Console.WriteLine(i.ToStringN0()); 

In the example, the class is placed in the System namespace, so it will be available through the application.

0
source share

If you create your own CultureInfo and you can change it, then assign it CultureInfo.CurrentCulture , as in this answer:

stack overflow

0
source share

This may help you:

Decimal.ToString (String) MSDN Method

DoubleToString (String) MSDN Method

asp.net mvc set number format default decimal thousand separators

-2
source share

All Articles