2012-07-27 59 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; 
     } 
    } 
}