This question already has an answer here:
I need to convert random numbers into KB, MB, GB and TB. For example, if 2048 is generated, it needs to display as 2KB.
I am not sure where to start with this, except for generating a random number:
$number = rand(1,1000000);
echo $number;
Would really appreciate if someone pointed me to the right direction.
</div>
You can round()
and following may help you. I use this code in production for a long time.
function convert_bytes_to_hr_format($size){
if (1024 > $size) {
return $size.' B';
} else if (1048576 > $size) {
return round( ($size / 1024) , 2). ' KB';
} else if (1073741824 > $size) {
return round( (($size / 1024) / 1024) , 2). ' MB';
} else if (1099511627776 > $size) {
return round( ((($size / 1024) / 1024) / 1024) , 2). ' GB';
}
}