2012-07-27 58 views
8

我一直在寻找这个,但似乎无法找到答案。我有一个对应的输出以下小数,我从希望的String.Format格式十进制c# - 保留最后的零

100.00 - > 100
100.50 - > 100.50
100.51 - > 100.51

我的问题是,我似乎无法找到格式,这将保持在100.50的末尾0以及从100中删除2个零。

任何帮助,非常感谢。

编辑 更清晰。我有小数类型的变量,他们只会有2位小数。基本上我想显示2位小数,如果他们有或没有,我不想在100.50的情况下,以显示小数点后一位成为100.5

+0

你想 “100.50”,成为 “1.50”? – 2012-07-27 07:42:51

+2

请举例! – 2012-07-27 07:43:07

回答

14

您可以使用此:

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

与tobias86的回答一样,这不适用于所有机器,因为有些机器使用逗号作为小数点分隔符。 – 2012-07-27 07:48:03

+0

+1,很好... – Heinzi 2012-07-27 08:39:51

+0

谢谢马克。抱歉应该对文化更加清楚,在这种情况下我可以忽略它。这工作完美。 – Peuge 2012-07-27 09:25:01

16

至于我知道,没有这样的格式。您必须手动执行此,例如:

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

'100。001'会使用'“0.00”'格式。 – 2012-07-27 07:48:49

+1

@MarkusJarderot:的确如此。只有OP可以回答这是否是期望的行为。他没有包含更多数字的例子。 – Heinzi 2012-07-27 08:18:26

+0

迄今为止最好的解决方案。感谢这 – 2016-01-30 18:59:27

2

好吧,这伤害了我的眼睛,但应该给你你想要的东西:

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

更新:我喜欢Heinzi的答案了。

+1

这不适用于我的机器,逗号是小数的默认值。 :) – 2012-07-27 07:46:54

+0

@AndersHolmström真的......我没有想到本地化。 – tobias86 2012-07-27 07:48:27

+5

没有人做过......(我在翻译公司工作:)) – 2012-07-27 07:49:15

5

测试,如果你的号码是一个整数,并根据使用的格式:

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

这种做法会达到预期的效果,同时将指定文化:

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 

您可以替换文化CultureInfo.CurrentCulture或任何其他文化来满足您的需求。

的类的CustomFormatter是:

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; 
     } 
    } 
}