razzv
razzv

Reputation: 85

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

I have some percentages and I don't know how to remove the zeroes. Meaning if I have 5.00% I want it to show 5%, however if I have 5.20% I want it to show 5.20%. I go through each member from a model and I have <span>@item.percentage</span>. How do I make it show up properly?

Upvotes: 2

Views: 898

Answers (3)

Matthew Watson
Matthew Watson

Reputation: 109762

This is a bit hacky but it works...

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

Here's a less hacky solution that works (and is therefore better):

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

Upvotes: 0

Hamid Pourjam
Hamid Pourjam

Reputation: 20764

You can check if the number has decimal places or not and generate appropriate result.

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

You can use it like this.

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

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

and result will be

5%
5.99%
3.20%

If you want to use it in razor then

@MyDoubleToString(item.percentage)

Upvotes: 1

tynar
tynar

Reputation: 136

@(item.percentage % 1==0 ? item.percentage.ToString("N0") : item.percentage.ToString("N2"))

Upvotes: 0

Related Questions