Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - easiest way to convert int to file size format (KB, MB or GB)?

Tags:

qt

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?

like image 244
Mas Bagol Avatar asked Jun 20 '15 19:06

Mas Bagol


People also ask

How do I get the size of a file in Qt?

You can simply use QFile::size() function to get size of file.

How do I convert MB to file size?

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 do you convert KB to MB?

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.

How to convert file size to KB MB in js?

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.


2 Answers

Qt 5.10 has introduced ready solution:

QLocale locale = this->locale();
QString valueText = locale.formattedDataSize(sizeValue);
like image 190
Marek R Avatar answered Sep 21 '22 02:09

Marek R


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;
}
like image 28
dfranca Avatar answered Sep 19 '22 02:09

dfranca