-1

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.

Anna Kurmanova
  • 141
  • 1
  • 7
  • Do you want to generate random number or do you want to get the size of actual files and show there size? – RiggsFolly Apr 12 '18 at 08:28
  • 2
    _“Would really appreciate if someone pointed me to the right direction.”_ - typing something rather trivial like _“php display file size in kb mb”_ into Google easily finds the duplicate. – CBroe Apr 12 '18 at 08:32
  • The thread got closed but I wanted to throw my suggestion that avoids multiple if statements and allows for easily adding more sizes if required; check out: https://3v4l.org/nY4V7 – IsThisJavascript Apr 12 '18 at 08:36
  • @CBroe glad typing trivial questions into Google works out for you but for me it didn't give me the result I wanted. Anything else? – Anna Kurmanova Apr 12 '18 at 08:37
  • @IsThisJavascript Thank you – Anna Kurmanova Apr 12 '18 at 08:38
  • 1
    Yes - please learn to research then, instead of using your lack of skills in that department as an excuse. – CBroe Apr 12 '18 at 08:38
  • Yeah I'm with CBroe on this one :X. The search term I'd use for this question would be "convert sizes in php stackoverflow" which would lead to that duplicate. Hopefully you can learn to get better at google fu – IsThisJavascript Apr 12 '18 at 08:41
  • @AnyaK You're being incredibly rude and that's going to hurt you when you come back to ask more questions on this site. – IsThisJavascript Apr 12 '18 at 09:21
  • @IsThisJavascript just answering in the same style as the other person. People have to learn somehow and this site is supposed to help with that. Obviously, I am a noob at PHP and sometimes I don't know how to ask a question, whether it's here or google. That, however, doesn't give anyone the right to be snotty and rude to me. – Anna Kurmanova Apr 12 '18 at 09:32

1 Answers1

2

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';
    }
}
Thamaraiselvam
  • 6,961
  • 8
  • 45
  • 71