Converting double to string with N decimals, dot as decimal separator, and no thousand separator

C#.NetStringDoubleDecimal

C# Problem Overview


I need to convert a decimal to a string with N decimals (two or four) and NO thousand separator:

'XXXXXXX (dot) DDDDD'

The problem with CultureInfo.InvariantCulture is that is places ',' to separate thousands.

UPDATE

This should work for decimal and double types.


My previous question: https://stackoverflow.com/questions/3971130/need-to-convert-double-or-decimal-to-string

C# Solutions


Solution 1 - C#

For a decimal, use the ToString method, and specify the Invariant culture to get a period as decimal separator:

value.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)

The long type is an integer, so there is no fraction part. You can just format it into a string and add some zeros afterwards:

value.ToString() + ".00"

Solution 2 - C#

It's really easy to specify your own decimal separator. Just took me about 2 hours to figure it out :D. You see that you were using the current ou other culture that you specify right? Well, the only thing the parser needs is an IFormatProvider. If you give it the CultureInfo.CurrentCulture.NumberFormat as a formatter, it will format the double according to your current culture's NumberDecimalSeparator. What I did was just to create a new instance of the NumberFormatInfo class and set it's NumberDecimalSeparator property to whichever separator string I wanted. Complete code below:

double value = 2.3d;
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = "-";
string x = value.ToString(nfi);

The result? "2-3"

Solution 3 - C#

You can use

value.ToString(CultureInfo.InvariantCulture)

to get exact double value without putting precision.

Solution 4 - C#

I prefer to use ToString() and IFormatProvider.

double value = 100000.3
Console.WriteLine(value.ToString("0,0.00", new CultureInfo("en-US", false)));

Output: 10,000.30

Solution 5 - C#

You can simply use decimal.ToString()

For two decimals

myDecimal.ToString("0.00");

For four decimals

myDecimal.ToString("0.0000");

This gives dot as decimal separator, and no thousand separator regardless of culture.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCaptain ComicView Question on Stackoverflow
Solution 1 - C#GuffaView Answer on Stackoverflow
Solution 2 - C#Pedro SantosView Answer on Stackoverflow
Solution 3 - C#MahiView Answer on Stackoverflow
Solution 4 - C#MakahView Answer on Stackoverflow
Solution 5 - C#Øyvind BråthenView Answer on Stackoverflow