How to convert a decimal number to an integer in Vue
Short article on how to convert an decimal number to an integer in Vue using parseInt method.
In this short tutorial, we will see how to convert a decimal number to an integer in Vue.
If we generate a random number using Math.random() function we get random decimal numbers like this :
Random number: 46.32594933788556
Now if we want to convert these values in our vue template to an integer (eg 46), then we can use the parseInt() method.
The parseInt() method analyzes a character string that is passed as an argument and converts it to an integer value.
Syntax :
parseInt(string);
So, using this method we can convert the number to an integer by passing the decimal number in parseInt() as an argument in our Vue template.
<template> <div id="app"> <div>Random number: {{ parseInt(randomNumber) }}</div> </div> </template>
Full code to convert the random value to an integer:
<template> <div id="app"> <div>Random number: {{ parseInt(randomNumber) }}</div> <button @click="generateNumber()">Generate Number</button> </div> </template> <script> export default { name: "App", data() { return { randomNumber: "", }; }, methods: { generateNumber() { this.randomNumber = Math.random() * 100; //multiply to generate random number between 0, 100 console.log(typeof this.randomNumber); }, }, }; </script>
Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
