簡體   English   中英

格式化十進制c# - 保持最后一個零

[英]Format decimal c# - Keep last zero

我一直在尋找這個,但似乎無法找到答案。 我有以下小數與我想要的String.Format相應的輸出

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

我的問題是我似乎無法找到一種格式,它將0保持在100.50的末尾,並從100中刪除2個零。

任何幫助深表感謝。

編輯更清晰。 我有十進制類型的變量,它們只會是2位小數。 基本上我想顯示2個小數位,如果它們存在或沒有,我不想在100.50變為100.5的情況下顯示一個小數位

據我所知,沒有這樣的格式。 您必須手動實現此功能,例如:

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

你可以用這個:

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

測試您的號碼是否為整數,並使用以下格式:

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

好吧,這會傷害我的眼睛,但應該給你你想要的東西:

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

更新:我更喜歡海因茲的回答。

應用指定的文化時,此方法將實現所需的結果:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM