...like it Windows Explorer does.
JavaScript code:
/**
* Formats bytes mostly like Windows does,
* but in some rare cases the result is different.
* Check the file with tests.
* @see https://github.com/AlttiRi/directory-snapshot-explorer/blob/master/tests/win-like-file-sizes.test.js
* @param {Number} bytes
* @return {string}
*/
function bytesToSizeWinLike(bytes) {
if (bytes < 1024) { return bytes + " B"; }
const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
let i = Math.floor(Math.log(bytes) / Math.log(1024));
let result = bytes / Math.pow(1024, i);
if (result >= 1000) {
i++;
result /= 1024;
}
return toTruncPrecision3(result) + " " + sizes[i];
}
/**
* @see https://github.com/AlttiRi/directory-snapshot-explorer/blob/master/tests/trunc-with-precision-3.test.js
* @param {Number} number
* @return {string}
*/
function toTruncPrecision3(number) {
let result;
if (number < 10) {
result = Math.trunc(number * 100) / 100;
} else if (number < 100) {
result = Math.trunc(number * 10) / 10;
} else if (number < 1000) {
result = Math.trunc(number);
}
if (number < 0.1) {
return result.toPrecision(1);
} else if (number < 1) {
return result.toPrecision(2);
}
return result.toPrecision(3);
}
See the test files to look at the input data and the corresponding output data:
- for
bytesToSizeWinLike
- for
toTruncPrecision3
The function's result is different from the Windows Explorer's result in some rare cases — see the test file.
But anyway the result of this function is the closest to the value that Windows Explorer shows, all existing functions on stackoverflow return a less closest result.
Taken from here: https://github.com/AlttiRi/directory-snapshot-explorer