Randy Minder
Randy Minder

Reputation: 48532

Why isn't my TextBoxFor displaying currency values correctly?

I have the following TextBoxFor on an MVC form:

<div class="col-xs-3">
   @Html.TextBoxFor(m => m.SalesSubTotal, null, new { @class = "form-control", title = "", @tabindex = "-1", @readonly = "readonly", @style = "text-align:right", Value = String.Format("{0:C2}", Model.SalesSubTotal) })
</div>

The user will never actually enter a value in this field. The field is always updated via a line in a JavaScript function that looks as follows:

$("#SalesSubTotal").val(salesSubTotal.toFixed(2));

When the page first displays the input displays $0.00 as I would expect. However, when the field is updated, the currency symbol is never displayed. So, instead of displaying something like $90.15, it displays 90.15.

Can someone see what I'm doing wrong?

Upvotes: 1

Views: 488

Answers (2)

Ricky Ruiz
Ricky Ruiz

Reputation: 26791

The string format is being applied when the element is rendered for the first time with Value = String.Format("{0:C2}", Model.SalesSubTotal), but then you change the value without that format in JS.

You can create a helper function that formats the value and use it like so:

(function() {

  function currencyFormat(val) {
    return `$${val.toFixed(2)}`;
  }

  let salesSubTotal = 90.1525346252;

  $("#SalesSubTotal").val(currencyFormat(salesSubTotal));

})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="SalesSubTotal">


Alternatively, you can extend the jQuery prototype with jQuery.fn.extend().

(function() {

  $.fn.extend({
    currencyVal: function(val) {
      this.val(`$${val.toFixed(2)}`);
    }
  });

  let salesSubTotal = 90.1525346252;

  $("#SalesSubTotal").currencyVal(salesSubTotal);

})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="SalesSubTotal">

Upvotes: 2

A Person
A Person

Reputation: 1112

Your number format {0:C2} isn't active anymore when javascript is invoked:

$("#SalesSubTotal").val(salesSubTotal.toFixed(2));

will actually just set the field to the value with two decimals just like you have experienced it. You have to add the dollar sign there aswell to get the correct result:

$("#SalesSubTotal").val("$" + salesSubTotal.toFixed(2));

Upvotes: 2

Related Questions