I have a data that has returns values of KB always.
Just wondering if this conversion is correct? Should it be 1024 instead of 1000?
It should display KB if its appropriate to show KB else show MB already when its appropriate to show in MB.
const fileSizeFormat = new Intl.NumberFormat("en-US", {
minimumFractionDigits: 1,
});
if (fileSize > 1000) {
convertedFileSize = `${fileSizeFormat.format(fileSize / 1000)} MB`;
} else {
convertedFileSize = `${fileSizeFormat.format(fileSize)} KB`;
}
2
Answers
If you’re assuming names litterally then your code is right:
1 kB = 1000 bytes
1 KiB = 1024 bytes
In your code, you’re converting to MB if the file size is greater than 1000 bytes. However, it might be more standard to use kilobytes until the size exceeds 1 MB.
It’s good practice to declare variables using const or let to avoid unintentional reassignment. I see convertedFileSize is used without prior declaration.
With these changes, your code will consistently use kilobytes until the file size exceeds 1 MB, at which point it switches to megabytes.
Also, make sure that the fileSize variable is defined before this code block. If it’s not, you might want to ensure it’s declared and assigned a value appropriately in your code.