Scanner
Scanner

Reputation: 617

Format decimal number to two places using Javascript with .NET MVC

I have 4 fields which are money 1, 2, 3 and Total, when a value is placed within money 1, 2, 3 an automatic calculation occurs and it appears in the Total field. However when I click the edit link all 4 fields are still populated however they are displayed to 4 decimal places (i.e 15.1511) instead of two decimal places (i.e 15.15). I've seen examples where other people have hardcoded their values into javascript however as shown in my code below I don't have hardcoded numeric values.

 <script type="text/javascript">
        function sum() {
            var txtFirstNumberValue = document.getElementById('money1').value;
            var txtSecondNumberValue = document.getElementById('money2').value;
            var txtThirdNumberValue = document.getElementById('money3').value;
            var result = parseFloat(txtFirstNumberValue) + parseFloat(txtSecondNumberValue) + parseFloat(txtThirdNumberValue);
            if (!isNaN(result)) {
                document.getElementById('Total').value = result.toFixed(2);
            }
        }
    </script>

My html View code is

@Html.LabelFor(model => model.Total, "Total", new { @class = "control-label col-md-5" })
<div class="col-md-offset-0">
    <input type="text" id="Total" name="Total" value="@Model.Total" />                                  
    @Html.ValidationMessageFor(model => model.Total)
</div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.money1, "money1", new { @class = "control-label col-md-5" })
    <div class="col-md-offset-0">
        <input type="text" id="money1" onkeyup="sum();" name="money1" value="@Model.money1"  />
        @Html.ValidationMessageFor(model => model.money1)
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.money2, "money2", new { @class = "control-label col-md-5" })
    <div class="col-md-offset-0">
        <input type="text" id="money2" onkeyup="sum();" name="money2" value="@Model.money2" />
        @Html.ValidationMessageFor(model => model.WeeklyRatesPayable)
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.money3, "money3", new { @class = "control-label col-md-5" })
    <div class="col-md-offset-0">
        <input type="text" id="money3" onkeyup="sum();" name="money3" value="@Model.money3" />
        @Html.ValidationMessageFor(model => model.money3)
    </div>
</div>

Is there a way of achieving this with javascript or formatting the input element?

Upvotes: 0

Views: 3488

Answers (2)

Scanner
Scanner

Reputation: 617

Solved my problem. I removed

<input type="text" id="MAXHB" onkeyup="sum();" name="MAXHB" value="@Model.MAXHB" />

And replaced it with

@Html.TextBoxFor(model => model.ContractualWeekly, "{0:C}", new { @class = "required numeric", onkeyup = "sum()" })

I did this for each of the four fields that I needed the decimal to be represented to two decimal places in Edit View. As an example my values now return as £15.24 instead of £15.2400.

Also for each of the fields that I needed to replace with TextBoxFor, I also modified my Model where these fields are so that they now look like

[Display(Name = "money")]
        [DisplayFormat(DataFormatString = "{0:c}", ApplyFormatInEditMode = true)]
        public Nullable<decimal> money { get; set; }

This ensures that when I select my Details View that each of the four values has a £ before the value.

Upvotes: 1

RattyLaa
RattyLaa

Reputation: 323

With a Money Type you can call ToString("C"); C stands for currency. I would be setting these to display as currency in each box before Javascript runs. Take a look at this related question as an example:

Formatting currency using display template in MVC

a HTML Helper has been created for this:

public static string Currency(this HtmlHelper helper, decimal data, string locale = "en-US", bool     woCurrency = false)
{
    var culture = new System.Globalization.CultureInfo(locale);

    if (woCurrency || (helper.ViewData["woCurrency"] != null && (bool)helper.ViewData["woCurrency"]))
        return data.ToString(culture);

    return data.ToString("C", culture);
}

then you can use it:

@Html.Currency(Model.Money);

Upvotes: 0

Related Questions