In this tutorial, we will learn how to round to 2 decimal places using Vue.js and the toFixed() method, which is used to convert a double number into two decimal places. You can also use the Tryit editor to edit and customize the code
How to Get 2 Digits after Decimal in Vue Js?
In Vue Js, you can round a number to two decimal places by using the toFixed(2) method, which rounds a given number to two decimal places.
Vue Format Number 2 Decimal Places
<div id="app">
<button @click="myFunction">Click me</button>
<p>Number: {{number}}</p>
<p>{{result}}</p>
</div>
<script type="module">
import { createApp } from 'vue'
createApp({
data()
{
return{
number:3.14567,
result:'',
}
},
methods:{
myFunction(){
this.result = 'Rounded Two Decimal Places: ' + this.number.toFixed(2)
}
}
}).mount('#app')
</script>
Output of above example
Example 2 : Vue 3 Round off to 2 Decimal Places
In the example below, we use Vue 3 to convert doubles to 2 decimal places. Please check the code below, customize it as per your preference, and use it in your project.
Used Composition API
<script type="module">
const {createApp,ref,computed} = Vue;
createApp({
setup() {
const numberToRound = ref(10.5678);
const roundedNumber = computed(() => {
return numberToRound.value.toFixed(2); // Rounds to 2 decimal places
});
return {
numberToRound,
roundedNumber
};
}
}).mount("#app");
</script>