Skip to content

Instantly share code, notes, and snippets.

@jspw
Created May 20, 2022 11:40
Show Gist options
  • Select an option

  • Save jspw/98176c690ae17ff4404dd16515b750f6 to your computer and use it in GitHub Desktop.

Select an option

Save jspw/98176c690ae17ff4404dd16515b750f6 to your computer and use it in GitHub Desktop.
Convert double kb size into kb, mb, gb, tb, pb
function (data) {
const result = {
size: -1,
unit: "Unknown"
};
const units = ["KB", "MB", "GB", "TB", "PB"];
let unitCount = 0;
if (data) {
try {
let size = parseFloat(data);
console.log("MHS : data parse -> " + size)
// `double | 0` converts double to int
// loop will continue until size less then 1024
while ((size / 1024 | 0) !== 0) {
size = size / 1024;
unitCount++;
}
result.size = size.toFixed(1);
result.unit = units[unitCount];
} catch (e) {
result.unit = units[unitCount];
}
} else result.unit = units[unitCount];
console.log(`MHS : FileSizeParserResult -> ${result}`);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment