I pull the hard drive size from a computer and then use PHP to convert it to it's human readable size (E.G 750GB)
The problem is, the advertised space in hard drives is not the same as the actual size of the hard drive, but I want my PHP to display the advertised size.
This is my code:
function formatBytes($size, $precision = 0) {
$base = log($size, 1024);
$suffixes = array('', 'KB', 'MB', 'GB', 'TB');
return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}
This is code that I found here on Stack. If I supply this with bytes for a 128GB
(128035676160 bytes
) hard drive, it actually displays 119GB
. The expected result is 128GB
. For a 1TB hard drive, the bytes are 1000204886016
, and the expected result is 1TB
or 1000GB
, but I actually get 931GB
.
A possible solution is to break the bytes string when the first 0
appears, and then I should have the expected result. 1
for 1tb, or 128
for 128GB. I'm just not sure if this will always work, and wanted a safer way to do this operation as it is important to my software.
I can't think of a logical way to do this, or even if it is possible. Any help with this problem is much appreciated.