[TIPS] Convert Your Numbers To Human Readable Format

Sometimes your code produce a large numbers which is hard for user to read it. For example 17753392783 bytes or 18293753038 unit. For human eyes, it is easier to get 17MB or 1 million rather than lot of numbers.

I write this as quick tips for you, in case you want to convert your data to human readable format. I do this in PHP, for other programming language you can get the algorithm and convert it to your own language:

function convert($numbers)
{
   $readable = array("",  "thousands", "millions", "billions");
   $index=0;
   while($numbers > 1000){
      $numbers /= 1000;
      $index++;
   }
   return("".round($numbers, 2)." ".$readable [$index]);
}

Usage:

echo convert(199000000);
// Will show 199.00 millions

Thank you for read this article. Good luck and have a nice day.

Comments

  1. Joe Negron Nyc says:

    I used your logic to do something similar in bash but used it for converting large numbers for file sizes (bytes) into a more human readable format such as KB, MB, GB, TB, Etc. I started with a similar array with the suffix values. I just wanted to say thanx.

    The quick article is on my blog — http://www.logicwizards.net/2010/10/19/byteme-a-simple-binary-metrics-bash-script-howto-convert-bytes-into-kb-mb-gb-etc-using-bash-bc/

  2. Thanks, man. Super simple and nice.

Give me your feedback

This site uses Akismet to reduce spam. Learn how your comment data is processed.