Skip to content
Related Articles

Related Articles

Improve Article

Convert decimal point numbers to percentage using filters in Vue.js

  • Last Updated : 17 Mar, 2021

Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries.

Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js template.

The conversion from a decimal number to percentage values can be done using filters. The logic of the filter will first check if the number is less than or equal to 1. When the user provides a number that is greater than 1, a message is displayed asking the user to enter a valid number, otherwise, we will multiply the number by 100 and return it by appending a percentage sign (%).

index.html




<html>
<head>
    <script src=
    </script>
</head>
<body>
    <div id='parent'>
        <p><strong>Decimal1: </strong>
          {{dec1}}
        </p>
        <p><strong>Percentage : </strong>
          {{ dec1 | percent }}
        </p>
        <p><strong>Decimal2: </strong>
          {{dec2}}
        </p>
        <p><strong>Percentage : </strong>
          {{ dec2 | percent }}
        </p>
        <p><strong>Decimal3: </strong>
          {{dec3}}
        </p>
        <p><strong>Percentage : </strong>
          {{ dec3 | percent }}
        </p>
        <p><strong>Decimal4: </strong>
          {{dec4}}
        </p>
        <p><strong>Percentage : </strong>
          {{ dec4 | percent }}
        </p>
  
    </div>
    <script src='app.js'></script>
</body>
</html>

app.js




const parent = new Vue({
    el: '#parent',
    data: {
        dec1: 0.1,
        dec2: 0.023,
        dec3: 0.47,
        dec4: 13
    },
  
    filters: {
        percent: function(dec) {
            if (dec <= 1) {
                return dec * 100 + "%";
            }
            return 'Please enter number less than or equal to 1'
        }
    }
})

Output:

Decimal to percentage using filter




My Personal Notes arrow_drop_up
Recommended Articles
Page :