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.I
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"
double value = 3.14159D;
string v = value.ToString().Replace(",", ".");
Console.WriteLine(v);
Output: 3.14159
You can use
value.ToString(CultureInfo.InvariantCulture)
to get exact double value without putting precision.
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"
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
I think you could have used:
value.ToString("F"+NumberOfDecimals)
value = 10,502
value.ToString("F2") //10,50
value = 10,5
value.ToString("F2") //10,50
Here is a detailed description of Numeric Format Strings