Format decimal c# - Keep last zero
Solution 1
You can use this:
string s = number.ToString("0.00");
if (s.EndsWith("00"))
{
s = number.ToString("0");
}
Solution 2
As far as I know, there is no such format. You will have to implement this manually, e.g.:
String formatString = Math.Round(myNumber) == myNumber ?
"0" : // no decimal places
"0.00"; // two decimal places
Solution 3
Test if your number is an integer, and use according format :
string.Format((number % 1) == 0 ? "{0}": "{0:0.00}", number)
Solution 4
Ok, this hurts my eyes, but should give you what you want:
string output = string.Format("{0:N2}", amount).Replace(".00", "");
UPDATE: I like Heinzi's answer more.
Solution 5
This approach will achieve the desired result while applying the specified culture:
decimal a = 100.05m;
decimal b = 100.50m;
decimal c = 100.00m;
CultureInfo ci = CultureInfo.GetCultureInfo("de-DE");
string sa = String.Format(new CustomFormatter(ci), "{0}", a); // Will output 100,05
string sb = String.Format(new CustomFormatter(ci), "{0}", b); // Will output 100,50
string sc = String.Format(new CustomFormatter(ci), "{0}", c); // Will output 100
You can replace the culture with CultureInfo.CurrentCulture or any other culture to fit your needs.
The CustomFormatter class is:
public class CustomFormatter : IFormatProvider, ICustomFormatter
{
public CultureInfo Culture { get; private set; }
public CustomFormatter()
: this(CultureInfo.CurrentCulture)
{ }
public CustomFormatter(CultureInfo culture)
{
this.Culture = culture;
}
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (formatProvider.GetType() == this.GetType())
{
return string.Format(this.Culture, "{0:0.00}", arg).Replace(this.Culture.NumberFormat.NumberDecimalSeparator + "00", "");
}
else
{
if (arg is IFormattable)
return ((IFormattable)arg).ToString(format, this.Culture);
else if (arg != null)
return arg.ToString();
else
return String.Empty;
}
}
}
Peuge
Updated on June 04, 2022Comments
-
Peuge almost 2 years
I have been searching for this but cannot seem to find the answer. I have the following decimals with the corresponding output that I want from String.Format
100.00 -> 100
100.50 -> 100.50
100.51 -> 100.51My problem is that I cannot seem to find a format which will keep the 0 on the end of 100.50 as well as remove the 2 zeros from 100.
Any help is much appreciated.
EDIT For some more clarity. I have variables of type decimal, they are only ever going to be 2 decimal places. Basically I want to display 2 decimal places if they exist or none, I don't want to display one decimal place in the case of 100.50 becoming 100.5