Home » vue » Vue js allow only 2 decimals in input without rounding

Vue js allow only 2 decimals in input without rounding

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m struggling with a problem. I want to disable more than 2 decimals in input.
Like the answer in this question: JQuery allow only two numbers after decimal point
But vuejs equivalent .

Answers:

Try to use a watch then check the input value and reset to the format that you want :

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',

  data() {
    return {
      num: 0
    }
  },
  watch: {
    num(newVal, oldVal) {


      if (newVal.includes('.')) {

        this.num = newVal.split('.')[0] + '.' + newVal.split('.')[1].slice(0, 2)
      }
    }
  }
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">
  <input type="number" class="number" v-model="num" />
</div>