0

In my ASP.NET Core 1.1 with EF Core 1.1, following View is displaying Cost value without dollar format. I would like to show it as, say, $1,945.25. Question: What I may be missing? Note: I tried this and this SO Posts but still the same issue.

Model:

public class costs
{
....
....        
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public float? Costs { get; set; }
....
....
}

TestViewModel:

public class TestViewModel
{
....
....  
public string ProdName{ get; set; }   
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public float? Costs { get; set; }
....
....
}

View:

@model myProj.Models.TestVewModel
....
....
<td>@Html.DisplayFor(t =>t.Cost)</td>

<td>@Html.EditorFor(t =>t.Cost)</td>
....
....

UPDATE:

The only difference I can think of between this post and this one may be that I'm using SQL Server 2012 that has data type real for costs column. But, I'm not sure if that is a reason for the issue. The real datatype was created via EF-Core migration commands.

nam
  • 21,967
  • 37
  • 158
  • 332
  • Well, for starters, don't use `float` for currency. Use `decimal`. Something as simple as .1 can't be accurately represented without using approximation logic. But, that's not your problem. I'm not entirely sure what your problem is.. is it just that it's not formatting correctly, even when using DisplayFormat attribute and DisplayFor/EditorFor? Looking at your code, you're placing your Attribute on the `costs` object, but you're using `TestVewModel` in your view. I know you say `TestViewModel` is "the same as above", but is it really? Why not just give us a small verifiable sample. – Erik Funkenbusch Jun 14 '17 at 20:51
  • FYI, see https://dotnetfiddle.net/2cGikc - This shows the value being correctly formatted. So obviously, you are doing something you're not showing us that is breaking it. – Erik Funkenbusch Jun 14 '17 at 21:03
  • @ErikFunkenbusch The problem is only related to data display not being formatted correctly. The values are displaying correctly but just as numbers like `1945.25` instead of `$1,945.25` I've tried DisplayFormat attribute and DisplayFor/EditorFor, as well. I've just added `TestViewModel` code and an **UPDATE** section if case it helps. Also, would changing `float` to `decimal` make any difference in actual values? – nam Jun 14 '17 at 21:53
  • 1
    as I said, float is not your problem, but you really don't want to use float for currency, because of floating point rounding errors. As you can see in the dotnetfiddle I linked you to, it works just fine to format using the attribute. It has nothing to do with sql server types. – Erik Funkenbusch Jun 14 '17 at 21:59

1 Answers1

0

If nothing works you can just one of these:

<td>$@t.Cost</td>

or

<td>@string.Format("{0:C}", t.Cost)</td>