2

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)"/>
deeej
  • 357
  • 1
  • 6
  • 22
  • Does this answer your question? [HTML5 Number Input - Always show 2 decimal places](https://stackoverflow.com/questions/22641074/html5-number-input-always-show-2-decimal-places) – RoboKozo Jun 18 '21 at 14:41
  • @RoboKozo unfortunately not. – deeej Jun 18 '21 at 14:56

4 Answers4

2

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.

Matt U
  • 4,970
  • 9
  • 28
  • This is a good solution. But what about when there are multiple input fields. I need to create a computed property for each of them? – deeej Jun 18 '21 at 15:30
  • Sure, or you can create a custom component that handles this internally. – Matt U Jun 18 '21 at 15:45
0

you should you step in input field:

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

afshar003
  • 765
  • 6
  • 6
  • Here is a link to the relevant documentation for the input element: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#allowing_decimal_values – RoboKozo Jun 18 '21 at 14:35
  • As you can see here. This makes no difference: https://jsfiddle.net/73ckwb4u/ – deeej Jun 18 '21 at 14:36
  • it does not show because it is all zero .if it was another number with show that. – afshar003 Jun 18 '21 at 14:45
0

This solves the problem:

<input class="form-control" type="number" :value="(this.solicitorsFees).toFixed(2)"/>
deeej
  • 357
  • 1
  • 6
  • 22
-1

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
    }
}
Yash Maheshwari
  • 1,842
  • 2
  • 7
  • 16