I\'m using this function to convert a file size in bytes to a human-readable file size:
function getReadableFileSizeString(fileSizeInBytes) {
var i = -1;
It depends on whether you want to use the binary or decimal convention.
RAM, for instance, is always measured in binary, so to express 1551859712 as ~1.4GiB would be correct.
On the other hand, hard disk manufacturers like to use decimal, so they would call it ~1.6GB.
And just to be confusing, floppy disks use a mixture of the two systems - their 1MB is actually 1024000 bytes.
A simple and short "Pretty Bytes" function for the SI system without the unnecessary fractionals rounding.
In fact, because the number size is supposed to be human-readable, a "1 of a thousand fraction" display is no longer human.
The number of decimal places is defaulted to 2 but can be modified on calling the function to other values. The common mostly display is the default 2 decimal place.
The code is short and uses the method of Number String Triplets.
Hope it is useful and a good addition to the other excellent codes already posted here.
// Simple Pretty Bytes with SI system
// Without fraction rounding
function numberPrettyBytesSI(Num=0, dec=2){
if (Num<1000) return Num+" Bytes";
Num =("0".repeat((Num+="").length*2%3)+Num).match(/.{3}/g);
return Number(Num[0])+"."+Num[1].substring(0,dec)+" "+" kMGTPEZY"[Num.length]+"B";
}
console.log(numberPrettyBytesSI(0));
console.log(numberPrettyBytesSI(500));
console.log(numberPrettyBytesSI(1000));
console.log(numberPrettyBytesSI(15000));
console.log(numberPrettyBytesSI(12345));
console.log(numberPrettyBytesSI(123456));
console.log(numberPrettyBytesSI(1234567));
console.log(numberPrettyBytesSI(12345678));
Solution as ReactJS Component
Bytes = React.createClass({
formatBytes() {
var i = Math.floor(Math.log(this.props.bytes) / Math.log(1024));
return !this.props.bytes && '0 Bytes' || (this.props.bytes / Math.pow(1024, i)).toFixed(2) + " " + ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][i]
},
render () {
return (
<span>{ this.formatBytes() }</span>
);
}
});
UPDATE For those using es6 here is a stateless version of this same component
const sufixes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const getBytes = (bytes) => {
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return !bytes && '0 Bytes' || (bytes / Math.pow(1024, i)).toFixed(2) + " " + sufixes[i];
};
const Bytes = ({ bytes }) => (<span>{ getBytes(bytes) }</span>);
Bytes.propTypes = {
bytes: React.PropTypes.number,
};
My answer might be late, but I guess it will help someone.
/**
* Format file size in metric prefix
* @param fileSize
* @returns {string}
*/
const formatFileSizeMetric = (fileSize) => {
let size = Math.abs(fileSize);
if (Number.isNaN(size)) {
return 'Invalid file size';
}
if (size === 0) {
return '0 bytes';
}
const units = ['bytes', 'kB', 'MB', 'GB', 'TB'];
let quotient = Math.floor(Math.log10(size) / 3);
quotient = quotient < units.length ? quotient : units.length - 1;
size /= (1000 ** quotient);
return `${+size.toFixed(2)} ${units[quotient]}`;
};
/**
* Format file size in binary prefix
* @param fileSize
* @returns {string}
*/
const formatFileSizeBinary = (fileSize) => {
let size = Math.abs(fileSize);
if (Number.isNaN(size)) {
return 'Invalid file size';
}
if (size === 0) {
return '0 bytes';
}
const units = ['bytes', 'kiB', 'MiB', 'GiB', 'TiB'];
let quotient = Math.floor(Math.log2(size) / 10);
quotient = quotient < units.length ? quotient : units.length - 1;
size /= (1024 ** quotient);
return `${+size.toFixed(2)} ${units[quotient]}`;
};
Examples:
// Metrics prefix
formatFileSizeMetric(0) // 0 bytes
formatFileSizeMetric(-1) // 1 bytes
formatFileSizeMetric(100) // 100 bytes
formatFileSizeMetric(1000) // 1 kB
formatFileSizeMetric(10**5) // 10 kB
formatFileSizeMetric(10**6) // 1 MB
formatFileSizeMetric(10**9) // 1GB
formatFileSizeMetric(10**12) // 1 TB
formatFileSizeMetric(10**15) // 1000 TB
// Binary prefix
formatFileSizeBinary(0) // 0 bytes
formatFileSizeBinary(-1) // 1 bytes
formatFileSizeBinary(1024) // 1 kiB
formatFileSizeBinary(2048) // 2 kiB
formatFileSizeBinary(2**20) // 1 MiB
formatFileSizeBinary(2**30) // 1 GiB
formatFileSizeBinary(2**40) // 1 TiB
formatFileSizeBinary(2**50) // 1024 TiB
Another embodiment of the calculation
function humanFileSize(size) {
var i = Math.floor( Math.log(size) / Math.log(1024) );
return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
};
This is size improvement of mpen answer
function humanFileSize(bytes, si=false) {
let u, b=bytes, t= si ? 1000 : 1024;
['', si?'k':'K', ...'MGTPEZY'].find(x=> (u=x, b/=t, b**2<1));
return `${u ? (t*b).toFixed(1) : bytes} ${u}${!si && u ? 'i':''}B`;
}
function humanFileSize(bytes, si=false) {
let u, b=bytes, t= si ? 1000 : 1024;
['', si?'k':'K', ...'MGTPEZY'].find(x=> (u=x, b/=t, b**2<1));
return `${u ? (t*b).toFixed(1) : bytes} ${u}${!si && u ? 'i':''}B`;
}
// TEST
console.log(humanFileSize(5000)); // 4.9 KiB
console.log(humanFileSize(5000,true)); // 5.0 kB