Search code examples
c#formatasp.net-core-mvccurrencymvcgrid

Can't set display format to 2 decimal places when using mvc6 grid


I need to display some average sums of currency values in my .net core asp mvc project.

I am using mvc 6 grid to display the data, and I have tried these solutions:

[DisplayFormat(DataFormatString = "{0:C}")]
public double? AverageCost { get; set; }

[DisplayFormat(DataFormatString = "{0:#.####}")]
public double? AverageCost { get; set; }

[RegularExpression(@"^\d+\.\d{0,2}$")]
public double? AverageCost { get; set; }

But still my values are displayed with several decimal places:

enter image description here

Am I missing something?

I know I can format the columns using the mvc 6 grid, but is there not a way of doing this in the ViewModel?

Note that this is NOT a duplicate of the suggested question.. If you actually read the questions you will see that.


Solution

  • I was able to do this by using the Formatted method and passing in the value {0:N} in the view itself:

    columns.Add(model => model.AverageCost).Titled("AverageCost").Formatted("{0:N}");
    

    I found the answer by getting the format string from here and finding the Formatted method used here

    This is perfect for me as it displays the values as currency but does not show the currency symbol as {0:C} does