Showing sum of values with two decimals

I'm having a list of items where one attribute is of type decimal.

When I try to sum the items attribute and display it with two decimals it won't work when the sum is even.

For example:

If sum is 30000 I want it to display 30000.00, now it shows just 30000.

But if the sum is 30000.55 it displays 30000.55.

My view code:

for (var j = 0; j < Model.Calculation.Count; j++)
{
     @Model.Calculation[j].Sum(item => item.InterestAmount).ToString("#.##")
}

How can I make it show 30000.00 when the sum is 30000?

Jon Skeet
people
quotationmark

You're using "#.##" as your format string, and # means "show a digit if it's significant". If you always want to show two digits, you should use "0.00" as your pattern. See the documentation for custom numeric format strings for more details.

Sample code:

using System;

class Test
{
    static void Main()
    {
        Show(0m);        // 0.00
        Show(0.123m);    // 0.12
        Show(123.456m);  // 123.46
        Show(-123.456m); // -123.46
    }

    static void Show(decimal value)
    {
        Console.WriteLine(value.ToString("0.00"));
    }
}

Note that this uses the current culture for formatting, so you could end up with "123,46" for example. If you always want a dot for the decimal separator, specify CultureInfo.InvariantCulture as the format provider.

people

See more on this question at Stackoverflow