1

I'm developing a ASP.NET MVC 4 application and I'm still a newbie for MVC. I noticed view render extra decimal places when I use Html.TextBox as follows.

    @Html.TextBox("OriginalContractAmt", Model == null ? 0 : Model.OriginalContractAmt, new { @readonly = true })

OriginalContractAmt property is a NotMapped field in the model and view shows the value as 479.4000.

I would like to force it to two decimal places. i.e. 479.40. How do I archive it? Tried following in the model and it didn't make any difference.

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0.0#}")]

Thanks in advance!

ecasper
  • 489
  • 1
  • 10
  • 30
  • 1
    "Also Model.OriginalContractAmt contains the expected value which is 479.4" - how have you checked that? (If it's via the immediate window, I suspect that may be at fault.) – Jon Skeet Jun 11 '14 at 16:12
  • I checked the value via watch window at both controller & view. – ecasper Jun 11 '14 at 16:23
  • 1
    My guess is that the value really *is* 479.4000m, but the watch window is truncating it. What happens if you call `Model.OriginalContractAmt.ToString()` in the watch window? – Jon Skeet Jun 11 '14 at 16:24
  • Model.OriginalContractAmt.ToString() returns 479.4000. so I was wrong about it. is there any global fix which can force the views to show only two decimal places? – ecasper Jun 11 '14 at 16:30
  • 1
    At that point, I'm out of my depth, I'm afraid. Happy that I moved the problem along a bit though - I suggest you edit your question appropriately. – Jon Skeet Jun 11 '14 at 16:30
  • 1
    The [DisplayFormat] attribute is only used in EditorFor/DisplayFor, and not by the raw HTML APIs like TextBoxFor.Try with Editor/EditorFor – malkam Jun 11 '14 at 17:26

3 Answers3

2

You can use Math.Round() to round the figure to 2 decimal places.

like:

@Html.TextBox("OriginalContractAmt", Model == null ? 0 : Math.Round(Model.OriginalContractAmt,2), new { @readonly = true })

If you don't want to round up or round down, then you can use truncate, as worked out by Hans Passant in here :

Truncate Two decimal places without rounding

Community
  • 1
  • 1
1

You could update like this, though it feels a bit like a hack:

@Html.TextBox("OriginalContractAmt", Model == null ? 0 : Decimal.Round(Model.OriginalContractAmt, 2), new { @readonly = true })

I'm assuming rounding would be fine, since you would lose the precision on postback, anyway.

Mike Guthrie
  • 4,029
  • 2
  • 25
  • 48
1

You're specifying the wrong mask:

  • 0 is compulsory digit
  • # is optional digit

So, the decimals places in this mask {0:0.0#} are:

  • 0: 1 compulsory decimal place
  • #: 1 optional decimal place

So, your mask should be {0:0.00}, i.e. two compulsory decimal places.

JotaBe
  • 38,030
  • 8
  • 98
  • 117