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

本文关键字:小数 何删除 删除 如果 | 更新日期: 2023-09-27 18:26:24

我有一些百分比,我不知道如何去除零。这意味着如果我有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)
@(item.percentage % 1==0 ? item.percentage.ToString("N0") : item.percentage.ToString("N2"))

这有点技巧,但它有效。。。

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 + "%";
}