Sandy
Sandy

Reputation: 275

Number Formatting in Mvc TextBox

I'd like to add a textbox in mvc that is 6 characters wide, with a decimal after 3 digits Like xxx.xx How can I do this. I am trying to do something like this but it is not giving desired output. Please share with me to sort this out. Thank You.

 @Html.TextBoxFor(m => m.Axis1_Amount, new { maxlength = "6" })
  $('#Amount').blur(function () {
            myFunction(this.value);
        });
        function myFunction(val) {
            getVal = parseFloat(Math.round(val * 100) / 100).toFixed(2);
            $("#Amount").val(getVal);
        }

Upvotes: 0

Views: 609

Answers (2)

Sandy
Sandy

Reputation: 275

As I am having a condition that my textbox will not contain more than 6 characters and referencing above given answer, I am solved my problem

  function FormatString(val) {
            getVal = 0;
            // getVal = parseFloat(Math.round(val) / 100).toFixed(2);
            if (val.length <= 3) {
                getVal = parseFloat(Math.round(val)).toFixed(2);
            }
            else if (val.length == 4) {
                getVal = parseFloat(Math.round(val) / 10).toFixed(2);
            }
            else if (val.length == 5) {
                getVal = parseFloat(Math.round(val) / 100).toFixed(2);
            }
            else if (val.length == 6) {
                getVal = parseFloat(Math.round(val) / 1000).toFixed(2);
            }
            $("#Amount").val(getVal);
        }

Upvotes: 0

Amit
Amit

Reputation: 15387

Try this

function myFunction(val) {
        getVal = parseFloat(Math.round(val) / 100).toFixed(2);
        $("#Amount").val(getVal);
    }

Demo

Upvotes: 1

Related Questions