Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

From The "#" Custom Specifier

The "#" custom format specifier serves as a digit-placeholder symbol. If the value that is being formatted has a digit in the position where the "#" symbol appears in the format string, that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string.

Note that this specifier never displays a zero that is not a significant digit, even if zero is the only digit in the string. It will display zero only if it is a significant digit in the number that is being displayed.

You might need to use 0.00 instead.

(30000).ToString("0.00") // Prints 30000.00
(30000.55).ToString("0.00") // Prints 30000.55

Of course this .ToString() method uses current thread culture by default. That's why your decimal separator depends on your current culture. If you always want . as a decimal separator, you need to provide a culture that has . as a NumberDecimalSeparator property like InvariantCulture.

Replace your "#" with 0

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

A simpler and far more efficient way to achieve this.

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

//  F:   0.00 
//  F0:  0 
//  F1:  0.0 
//  F2:  0.00 
//  F3:  0.000 

For more such formats related to numbers visit here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top