One challenge I am facing in my Angular application is converting bytes to units such as MB, GB, etc.
The data I need for conversion is coming from the backend. For instance, I have data on All RAM, Available RAM, and Used RAM. These values are stored as integers, and I am simply trying to convert them. The formula for "Available RAM" is calculated by subtracting Used RAM from All RAM, and sometimes this results in a negative value which should be valid in our context.
However, the current function I am using does not handle negative values correctly.
Here is the function snippet:
const SIZES = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
formatBytes(bytes, decimals = 1) {
for (var i = 0, r = bytes, b = 1024; r > b; i++) r /= b;
return `${parseFloat(r.toFixed(decimals))} ${SIZES[i]}`;
}
I attempted to include an if statement checking for bytes < 0, but unfortunately that did not resolve the issue.