Skip to content
Related Articles

Related Articles

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

Improve Article
Save Article
  • Last Updated : 31 Mar, 2021
Improve Article
Save Article

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.


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


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";


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!