Converting double to string with N decimals, dot as decimal separator, and no thousand separator
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"
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"
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