Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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?

like image 575
nbokmans Avatar asked Jan 02 '23 05:01

nbokmans


2 Answers

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.

like image 132
Chris Pratt Avatar answered Jan 24 '23 14:01

Chris Pratt


Another way to stop the tag-helper from applying this default formatting is to explicitly specify the input element's type attribute and assign it as text like so:

<input type="text" asp-for="RatePercentage" …/>

Then you get the 'raw' decimal value in the input control and you can use an edit-mask or format it yourself some other way and not automatically lose the precision of the value that happens otherwise.

like image 32
Christopher King Avatar answered Jan 24 '23 12:01

Christopher King