Vue.Js 2 Input formatting number

16,423

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.

Share:
16,423
Joshua Lee
Author by

Joshua Lee

Updated on June 04, 2022

Comments

  • Joshua Lee
    Joshua Lee almost 2 years

    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.

    • Christhofer Natalius
      Christhofer Natalius over 5 years
      Try out vue-cleave-component It has so many options, including currency
  • Joshua Lee
    Joshua Lee over 5 years
    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
  • TommyF
    TommyF over 5 years
    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).