Skip to content
Related Articles

Related Articles

Improve Article

Data Conversion to KB, MB, GB, TB using Vue.js filters

  • Last Updated : 31 Mar, 2021

In this article, we are going to learn how to convert data to the given unit of data using filters in VueJS. 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 abbreviation of the data values to KB, MB, GB, or TB can be done using a filter. The logic of the filter will first divide the value by 1024 raised to the power of a constant. For example, to convert the value in Kilobytes, the constant is assumed to 1, similarly, for a value in Megabytes, the constant value is 2, and so on.

The below example will demonstrate this approach:

Example: In this example, we will convert various values of bytes to the given unit of data given to the filter.

index.html






<html>
<head>
  <script src=
  </script>
</head>
<body>
  <div id='parent'>
    <h1 style="color: green;">
      GeeksforGeeks
    </h1>
    <p><strong>Bytes: </strong>{{d1}}B</p>
  
    <p><strong>MegaBytes : </strong>
      {{ d1 | bytes('MB') }}
    </p>
  
    <p><strong>Bytes: </strong>{{d2}}B</p>
  
    <p><strong>KiloBytes : </strong>
      {{ d2 | bytes('KB') }}
    </p>
  
    <p><strong>Bytes: </strong>{{d3}}B</p>
  
    <p><strong>TeraBytes : </strong>
      {{ d3 | bytes('TB') }}
    </p>
  
    <p><strong>Bytes: </strong>{{d4}}B</p>
  
    <p><strong>GigaBytes : </strong>
      {{ d4 | bytes('GB') }}
    </p>
  
  </div>
  <script src='app.js'></script>
</body>
</html>

app.js




const parent = new Vue({
  el: "#parent",
  
  // Define the data to be converted
  data: {
    d1: 200000,
    d2: 1024,
    d3: 3532283533343,
    d4: 24322664648,
  },
  
  filters: {
    bytes: function (data, to) {
      const const_term = 1024;
  
      // Convert the values and concatenate
      // the appropriate unit
      if (to === "KB") {
        return (data / const_term).toFixed(3) + "KB";
      } else if (to === "MB") {
        return (data / const_term ** 2).toFixed(3) + "MB";
      } else if (to === "GB") {
        return (data / const_term ** 3).toFixed(3) + "GB";
      } else if (to === "TB") {
        return (data / const_term ** 4).toFixed(3) + "TB";
      } else {
        return "Please pass valid option";
      }
    },
  },
});

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :