javascript function convert bytes into mb 1

javascript function convert bytes into mb

function niceBytes(x){
 const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  let l = 0, n = parseInt(x, 10) || 0;
  while(n >= 1024 && ++l){
      n = n/1024;
  }
  return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
}

Here is what the above code is Doing:
1. We’re creating a function called niceBytes.
2. We’re creating an array called units.
3. We’re creating a variable called l and setting it to 0.
4. We’re creating a variable called n and setting it to the value of x.
5. We’re creating a while loop that will run as long as n is greater than or equal to 1024 and l is greater than 0.
6. We’re incrementing l by 1.
7. We’re setting n to n divided by 1024.
8. We’re returning the value of n.toFixed(n < 10 && l > 0 ? 1 : 0) + ‘ ‘ + units[l].

Similar Posts