Qt - easiest way to convert int to file format (KB, MB or GB)?
4 answers
QFileInfo doesn't have a method for this, but here you can find a simple implementation of subclassing QFileInfo and implement 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;
}
+11
source to share
Qt 5.10 has implemented a ready-made solution :
QLocale locale = this->locale();
QString valueText = locale.formattedDataSize(sizeValue);
+1
source to share
The code provided by @danielfranca produces slightly incorrect results when used with int rather than floating point. Here is a more accurate version for reporting the result as a whole:
QString MyClass::convertFileSizeToHumanReadable(const qlonglong & bytes)
{
QString number;
if(bytes < 0x400) //If less than 1 KB, report in B
{
number = QLocale::system().toString(bytes);
number.append(" B");
return number;
}
else
{
if(bytes >= 0x400 && bytes < 0x100000) //If less than 1 MB, report in KB, unless rounded result is 1024 KB, then report in MB
{
qlonglong result = (bytes + (0x400 / 2)) / 0x400;
if(result < 0x400)
{
number = QLocale::system().toString(result);
number.append(" KB");
return number;
}
else
{
qlonglong result = (bytes + (0x100000 / 2)) / 0x100000;
number = QLocale::system().toString(result);
number.append(" MB");
return number;
}
}
else
{
if(bytes >= 0x100000 && bytes < 0x40000000) //If less than 1 GB, report in MB, unless rounded result is 1024 MB, then report in GB
{
qlonglong result = (bytes + (0x100000 / 2)) / 0x100000;
if(result < 0x100000)
{
number = QLocale::system().toString(result);
number.append(" MB");
return number;
}
else
{
qlonglong result = (bytes + (0x40000000 / 2)) / 0x40000000;
number = QLocale::system().toString(result);
number.append(" GB");
return number;
}
}
else
{
if(bytes >= 0x40000000 && bytes < 0x10000000000) //If less than 1 TB, report in GB, unless rounded result is 1024 GB, then report in TB
{
qlonglong result = (bytes + (0x40000000 / 2)) / 0x40000000;
if(result < 0x40000000)
{
number = QLocale::system().toString(result);
number.append(" GB");
return number;
}
else
{
qlonglong result = (bytes + (0x10000000000 / 2)) / 0x10000000000;
number = QLocale::system().toString(result);
number.append(" TB");
return number;
}
}
else
{
qlonglong result = (bytes + (0x10000000000 / 2)) / 0x10000000000; //If more than 1 TB, report in TB
number = QLocale::system().toString(result);
number.append(" TB");
return number;
}
}
}
}
}
0
source to share