For example I have several decimals:
decimal[] arr = { 1, (decimal)1.1, (decimal)1.00 };
they represent price in russian rubles:
var overrideCulture = new System.Globalization.CultureInfo("ru-RU");
when I use:
foreach (var d in arr)
{
string s = d.ToString("c", overrideCulture);
Console.WriteLine(s);
}
I get
1,00p.
1,10p.
1,00p.
as result, but what I need is, if fraction is zero, I don’t want it to be displayed but I need to keep currency format. in this example I want to get:
1p.
1,10p.
1p.
I can simply get of fractions like:
foreach (var d in arr)
{
string s = d.ToString("#.##", overrideCulture);
Console.WriteLine(s);
}
but currency format will be lost.
string s = d.ToString("#.##c", overrideCulture);
also does’n work, I get 1c or 1,1c
Is there some NOT tricky way to get such formatting like I need?
I don’t know of a single format string that will do that but one way would be:
if d may have more than 2 decimal places and you want to not show decimals for any value that would round to
.00tryAs a side note you can avoid a cast be defining the constants as decimal literals: