1

The code is as follows.

function formatBytes(bytes,decimals) {
   if(bytes == 0) return '0 Byte';
   var k = 1000; // or 1024 for binary
   var dm = decimals + 1 || 3;
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
   var i = Math.floor(Math.log(bytes) / Math.log(k));
   return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

But I don't know how to use Math.log().

Correct way to convert size in bytes to KB, MB, GB in Javascript

Community
  • 1
  • 1
Tomorrow
  • 11
  • 3
  • Could you add some more info to your post? What is the expected behaviour and what is not working for you? – s952163 Jun 17 '16 at 03:59

2 Answers2

1

The Math.log() function returns the natural logarithm (base e) of a number, that is

∀x>0,Math.log(x) = ln(x)= the unique y such that e^y=x

var i = Math.floor(Math.log(bytes) / Math.log(k));

i will be index of sizes


For example: bytes < 1000 => i = 0 because floor method rounds a number downward to its nearest integer.

ThiepLV
  • 1,219
  • 3
  • 10
  • 21
1

Consider that the size units bytes, KB, MB, GB etc. are in successive powers of 1024, as in 1024^0, 1024^1, 1024^2 and so on.

So to know which unit to use for an arbitrary number of bytes, one needs to calculate the highest power of 1024 below it.

The integral part of a postive valued base 2 logarithm, ln2( bytes), is the power of two below it, so an easy way to obtain the power of 1024 below a number is to divide its base 2 logarithm by 10, since 1024 is 2^10, and take the integral part.

This yields a function

function p1024( n) { return Math.floor(Math.log2( n) / 10);}

to use as an index into the units abbreviation array.

The posted code is using mathematical knowledge that ln2( n) / 10 is equivalent to ln( n) / ln(1024), where ln is the natural logarithm function and ln2 is a function for base 2 logarithms.


In Javascript Math is a global object which is accessible to all javascript code. In Java you may need to import java.lang.Math or java.lang.* before use (not a Java expert here).

traktor
  • 17,588
  • 4
  • 32
  • 53