如果小数为零,如何删除小数?

How to remove the decimals in case if they are zero?

我有一些百分比,但我不知道如何删除零。意思是如果我有 5.00% 我希望它显示 5%,但是如果我有 5.20%我希望它显示 5.20%。 我从一个模型中检查每个成员,我有 <span>@item.percentage</span>。如何让它正确显示?

您可以检查数字是否有小数位并生成适当的结果。

public static string MyDoubleToString(double d)
{
    // preventing rounding
    // if you want 5.9999 becomes 6 then comment the line below
    d = Math.Truncate(d * 100) / 100;

    return $"{d.ToString("f2")}%".Replace(".00%", "%");
}

你可以这样使用它。

var doubles = new double[] { 5.0, 5.999, 3.2 };

foreach (var d in doubles)
    Console.WriteLine(MyDoubleToString(d));

结果将是

5%
5.99%
3.20%

如果你想在剃须刀中使用它,那么

@MyDoubleToString(item.percentage)

这有点 hacky 但它有效...

public static string FormatDecimalWithPercent(decimal d, int decimalPlaces)
{
    string format = "{0:f" + decimalPlaces + "}";

    string candidate = string.Format(format, d);
    string trimmed = candidate.TrimEnd('0');

    if (trimmed.EndsWith("."))
        return trimmed.TrimEnd('.') + "%";

    return candidate + "%";
}

这里有一个不太复杂的解决方案(因此更好):

public static string FormatDecimalWithPercent(decimal d, int decimalPlaces)
{
    decimal rounded   = decimal.Round(d, decimalPlaces);
    decimal truncated = decimal.Round(d, 0);

    if (rounded != truncated)
        return string.Format("{0:f" + decimalPlaces + "}", rounded) + "%";

    return truncated + "%";
}
@(item.percentage % 1==0 ? item.percentage.ToString("N0") : item.percentage.ToString("N2"))