Search code examples
asp.net-coreasp.net-core-tag-helpers

.netcore asp-for decimal loses decimal places


I am running into an issue where I am losing decimal places when using the asp-for tag helper in my view. It seems to always round up to 2 decimals, while I want to have it round up to 3 decimals (in this case).

I can see in my debugger that the value in the Model has 3 decimal places as eenter image description here

But then in my view, it's being displayed as 1.28 instead of 1.275: enter image description here

This is my form's view, as you can see there's nothing special really going on (the asp-has-error tag helper is a custom tag helper for this project):

<div class="form-group row">
        <label asp-for="RatePercentage" class="col-lg-4 col-form-label"></label>
        <div class="col-lg-8">
                <input asp-for="RatePercentage" asp-has-error="@Html.HasErrorFor(m => m.RatePercentage)" class="form-control"/>
        </div>
</div>

Any ideas how I can get 3 decimal places to show here?


Solution

  • That's just the default. You can use the DisplayFormat attribute to make it whatever you like:

    [DisplayFormat(DataFormatString = "{0:[format]}", ApplyFormatInEditMode = true)]
    public decimal RatePercentage { get; set; }
    

    Where [format] is the format string you want. See Standard Numeric Format Strings and Custom Numeric Format Strings.