1

I've been struggling to find a nice algorithm to change a number (could be a float or integer) into a nicely formated human readable number showing the units as a string. For example:

100500000 -> '100.5 Mil'
200400 -> '200.4 K'
143000000 -> '143 Mil'
52000000000 -> '52 Bil'

etc, you get the idea.

Any pointers?

1
  • Be sure to take i18n into account and use the correct decimal point separator for the current locale - e.g., comma in Germany. :-)
    – JeeBee
    Jun 4, 2009 at 23:08

5 Answers 5

6

I'd adapt the code below (which i found on the net):

Code credit goes to this link i found: http://www.phpfront.com/php/human-readable-byte-format/

function humanReadableOctets($octets)
{
    $units = array('B', 'kB', 'MB', 'GB', 'TB'); // ...etc

    for ($i = 0, $size =$octets; $size>1024; $size=$size/1024)
        $i++;

    return number_format($size, 2) . ' ' . $units[min($i, count($units) -1 )];
} 

Don't forget to change 1024 to 1000 though ...

1
  • 6
    You could actually just do something alone the lines of $unit = $units[log($n)]
    – n3rd
    Jun 4, 2009 at 23:12
4
<?php

function prettyNumber($number) // $number is int / float
{
  $orders = Array("", " K", " Mil", " Bil");
  $order=0;
  while (($number/1000.0) >= 1.5) {  // while the next step up would generate a number greater than 1.5
    $order++;
    $number/=1000.0;
  }
  if ($order) 
    return preg_replace("/\.?0+$/", "", 
      substr(number_format($number, 2),0,5)).$orders[$order];
  return $number;
}

$tests = array(100500000,200400,143000000,52000000000);
foreach ($tests as $test)
{
  echo $test." -> '".prettyNumber($test)."'\n";
}
1
  • I like it. I especially like the tests included.
    – Christian
    Jun 4, 2009 at 23:20
2

Here is a log() version if you are still interested:

function wordify($val, $decimalPlaces = 1) {
    if ($val < 1000 && $val > -1000)
        return $val;
    $a = array( 0 => "", 1 => "K", 2 => "Mil", 3 => "Bil", 4 => "Tril", 5 => "Quad" );
    $log1000 = log(abs($val), 1000);
    $suffix = $a[$log1000];
    return number_format($val / pow(1000, floor($log1000)), $decimalPlaces, '.', '') . " $suffix";
}

$tests = array(-1001, -970, 0, 1, 929, 1637, 17000, 123456, 1000000, 1000000000, 1234567890123);

foreach ($tests as $num) {
    echo wordify($num)."<br>";
}
0
0

found this

this one might be better for you

might be a good start

0

there is similar code here:

http://aidanlister.com/2004/04/human-readable-file-sizes/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.