What is the easiest way to convert int
of file size to string in file size format like:
2048 to 2 KB
4086 KB to 4 MB
instead of calculating it manually in Qt5?
You can simply use QFile::size() function to get size of file.
zip"); // Get length of file in bytes long fileSizeInBytes = file. length(); // Convert the bytes to Kilobytes (1 KB = 1024 Bytes) long fileSizeInKB = fileSizeInBytes / 1024; // Convert the KB to MegaBytes (1 MB = 1024 KBytes) long fileSizeInMB = fileSizeInKB / 1024; if (fileSizeInMB > 27) { ... }
How to convert KiloBytes to MegaBytes? To convert between KB and MB you need to divide by 1000 if using the SI convention and by 1024 if using the binary convention.
To convert file size to MB in JavaScript, we can divide the number of bytes by 1024 raise to the power of 2. to define the bytesToMegaBytes function that divide bytes by 1024 ** 2 . Therefore, we get 4.459150314331055 logged as a result.
Qt 5.10 has introduced ready solution:
QLocale locale = this->locale();
QString valueText = locale.formattedDataSize(sizeValue);
QFileInfo doesn't have a method specific for that, but here you can find a simple implementation subclassing QFileInfo and implementing this new method
QString QFileInfoHumanSize::size_human()
{
float num = this->size();
QStringList list;
list << "KB" << "MB" << "GB" << "TB";
QStringListIterator i(list);
QString unit("bytes");
while(num >= 1024.0 && i.hasNext())
{
unit = i.next();
num /= 1024.0;
}
return QString().setNum(num,'f',2)+" "+unit;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With