C # decimal number format - keep last zero

I searched for this, but did not seem to find an answer. I have the following decimal places with the corresponding output that I want from String.Format

100.00 → 100
100.50 → 100.50
100.51 → 100.51

My problem is that I cannot find a format that will save 0 at the end of 100.50 and also remove 2 zeros from 100.

Any help is greatly appreciated.

EDIT For clarity. I have decimal type variables, they will only ever be 2 decimal places. Basically I want to display 2 decimal places, if they exist or not, I don't want to display one decimal place in case of 100.50, becoming 100.5

+8
c # string-formatting
source share
5 answers

You can use this:

string s = number.ToString("0.00"); if (s.EndsWith("00")) { s = number.ToString("0"); } 
+14
source share

As far as I know, there is no such format. You will have to implement this manually, for example:

 String formatString = Math.Round(myNumber) == myNumber ? "0" : // no decimal places "0.00"; // two decimal places 
+16
source share

Check if your number is an integer and use the format:

 string.Format((number % 1) == 0 ? "{0}": "{0:0.00}", number) 
+5
source share

Well, it hurts my eyes, but should give you what you want:

 string output = string.Format("{0:N2}", amount).Replace(".00", ""); 

UPDATE: I like that Heinzi answered more.

+2
source share

This approach will achieve the desired result when 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 CultureInfo.CurrentCulture culture or any other culture to suit your needs.

CustomFormatter Class:

 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; } } } 
+1
source share

All Articles