Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default number format for ToString

Is it possible to define a default number format that is used whenever I convert an integer (or double etc.) to a 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);

ASP.NET Razor example:

<div>
    Hello @i
</div>

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

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

I already found the question Set Default DateTime Format c# - it looked good, but it doesn't help me for numbers.


Edit: I'm aware that I could write an extension method which I can use throughout my application, but this is not what I'm looking for. I would like to find a property (maybe somewhere hidden in CultureInfo or NumberFormatInfo) which is currently set to "G" and is used by the default Int32.ToString() implementation.

like image 808
fero Avatar asked Feb 26 '14 12:02

fero


People also ask

What is numeric format?

Numeric data types can be instructed to format and parse scientific notation only via a pattern. In a pattern, the exponent character immediately followed by one or more digit characters indicates scientific notation. Example: "0. ###E0" formats the number 1234 as "1.234E3".

How do you convert decimal to ToString?

To convert a Decimal value to its string representation using a specified culture and a specific format string, call the Decimal. ToString(String, IFormatProvider) method.

What is ToString N0?

ToString("N0") is supposed to print the value with comma separators and no decimal points.

What is numeric formatting in C#?

Number Format SpecifierThis Format Specifier can be used to convert a number into a string of the form "-d,ddd,ddd. ddd....." where d represents any number between 0 to 9. The negative sign represents a negative number and "." denotes the decimal point in the number and "," denotes the group separator.


1 Answers

If you create your own CultureInfo and you can alter it and then assign it to CultureInfo.CurrentCulture like in this answer:

https://stackoverflow.com/a/24785761/166921

like image 158
Kamil Szot Avatar answered Sep 28 '22 17:09

Kamil Szot