0

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?

Scanner
  • 597
  • 1
  • 9
  • 19
  • With the JavaScript code you've shown, you'll only have two digits to the right of the `.` in the `Total` field, because you're (correctly) using `.toFixed(2)`. – T.J. Crowder Jan 02 '15 at 13:14
  • Use accounting.js and save yourself a lot of headache in money formatting. http://openexchangerates.github.io/accounting.js/ – David East Jan 02 '15 at 13:14
  • Thanks for the suggestions guys. @T.J. intellisense won't let me use .toFixed(2) for the other three 3 fields. But even with the Total field when its being edited its fine as it stays to 2 decimal places but when I save it and re-click the edit link it displays again with 4 deciamls. – Scanner Jan 02 '15 at 13:22
  • @Scanner: What do you mean "the other three fields"? In the above, you keep them as strings until the line where you add them together. Strings don't have `toFixed`; numbers do. – T.J. Crowder Jan 02 '15 at 13:37
  • @T.J: money 1, 2, 3 are the other three I was referring to. The whole problem is when they are being redisplayed after clicking the edit button. In display and create they show up fine, it's just when redisplayed in edit they show up with 4 decimal places after the . – Scanner Jan 02 '15 at 13:42

2 Answers2

1

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.

Scanner
  • 597
  • 1
  • 9
  • 19
0

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);
Community
  • 1
  • 1
RattyLaa
  • 323
  • 3
  • 12