4

I have been struggling to get a number input to format numbers using vuejs2.

Migrating some view logic from asp.net core 2 to vue and I was using this:

<input asp-for="Model.LoanAmount" value="@(Model.LoanAmount > 0 ? Model.LoanAmount.ToString("N2") : String.Empty)" >

but that required me to reload that view onchange of the input.

I need a way to format number inputs with US format and 2 decimal places, (1,000,000.21) but to display nothing when the model value is zero or empty.
vue-numeric does ALMOST everything, but fails for me when I try to use a placeholder.

<vue-numeric v-model="vm.loanAmount" seperator="," placeholder=" " :precision="2" ></vue-numeric> 

I tried using a space for placeholder because it crashes when I use an empty string. This example displays 0.00 if zero or empty is inputted. I tried playing with the output-type and empty-value props.

I'm not wedded to vue-numeric but it is handy because I don't know of a more convenient solution.

1

1 Answer 1

3

You can achieve the formatting by simply using a computed property with separate getter and setter without the need for other dependencies.

computed: {
  formattedValue: {
    get: function() {
      return this.value;
    },
    set: function(newValue) {
      if (newValue.length > 2) {
        newValue = newValue.replace(".", "");
        this.value =
          newValue.substr(0, newValue.length - 2) +
          "." +
          newValue.substr(newValue.length - 2);
      } else {
        this.value = newValue;
      }
    }
  }
}

https://codesandbox.io/s/p7j447k7wq

I only added the decimal separator as an example, you'll have to add the , thousand separator in the setter for your full functionality.

Sign up to request clarification or add additional context in comments.

2 Comments

I followed this advice but it doesn't do exactly what I need, computed property setter sets immediately), I need something that will only format on change of the input. I also found the handy Number.prototype.toLocaleString() method built in to js. For now I am using a method because idk a way to get computed property to only update on change event
You can't get a computed property to only update on change, the entire point of a computed value is to reflect any change in the values it depends/computes on. You can however simply call your formatting as a method call on change (i.e. don't use a computed property, use a method to format and a simple v-model).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.