How do I display a value as a decimal place in vuejs input field?

Viewed 5154

I'm trying to display a 2000.00 in an input field in vuejs but it strips the .00.

<div id="app">
   <input
    class="form-control"
    type="number"
    v-model="solicitorsFees"/>
</div>

new Vue({
  el: "#app",
  data: {
   solicitorsFees: 2000.00,
  },
})

How do I get the input field to display 2000.00?

jsfiddle

I can do this with a calculated property. But I need to apply this to multiple input fields.

solicitorsFeesDecimal: function(){
  return(this.solicitorsFees.toFixed(2))
},

 

<input class="form-control" type="number" v-model="solicitorsFeesDecimal"/>

Solution:

<input class="form-control" type="number" :value="(this.solicitorsFees).toFixed(2)"/>
4 Answers

The appropriate solution is to use a computed property with a custom getter and setter, as well as using the v-model.number modifier:

Template

<div id="app">
   <input
    class="form-control"
    type="number"
    v-model.number="solicitorsFeesDisplay"/>
</div>

Script

new Vue({
  el: "#app",
  computed: {
    solicitorsFeesDisplay: {
      get: function() {
        return this.solicitorsFees.toFixed(2)
      },
      set: function(newValue) {
        this.solicitorsFees = newValue
      }
    }
  },
  data() {
    return {
      solicitorsFees: 2000.00
    }
  },
})

See a working example on CodeSandbox.

This solves the problem:

<input class="form-control" type="number" :value="(this.solicitorsFees).toFixed(2)"/>

you should you step in input field:

<input type="number" v-model="solicitorsFees" step="0.01">

You can simply use parseFloat and toFixed together to define the number of decimal places you want.

v-model= parseFloat(solicitorsFees).toFixed(2)

Also, another suggestion is to make the data object as a function, as in your fiddle you are using an object.

data () {
    return {
        solicitorsFees: 2000.00
    }
}
Related