jqueryasp.net-mvcmaskjquery-mask

Jquery Mask Plugin removes decimal zeros


I am using jQuery Mask Plugin in my MVC .Net project. In a bootstrap modal a form is shown which contains a field of type currency.

@Html.TextBoxFor(model => model.Amount, new { @class = "form-control", data_mask = "#,##0.00", data_mask_reverse = "true" })

That modal is used to insert or edit records.

When I open the modal to insert, the mask works perfect.

When I open the modal to edit, the data from the currency field should be loaded into the field, but the mask was not applied to the field. To solve that problem, I did the following when opening the modal.

$("#Amount").trigger("input");

And it worked perfect.

The problem I have is that if when registering an amount of for example 12,345.00 in the field. When I open the modal for editing, the zeros that are decimal are removed, showing in the field the amount 123.45.

But, if I register 1,234.56, when I open the modal to edit, the same value 1,234.56 is shown correctly in the field.

What can I do so that when the decimals are zeros, the mask continues to keep them?


Solution

  • I continued to review my problem and found that it is not the mask that is causing it. Apparently the problem occurs from the $.parseJSON that the fields of type numbers when converting a value that has zeros as decimals keeps it as a 0.

    How to prevent removing decimal point when parsing JSON?

    So my quick fix (I don't know if it's the best or the correct one) was to do the following when assigning the value to the field.

    $("#Amount").val(amountNum.toFixed(2));