views:

277

answers:

5

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?

A: 

found this

this one might be better for you

might be a good start

Fredou
A: 

there is similar code here:

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

動靜能量
+2  A: 
<?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";
}
gnarf
I like it. I especially like the tests included.
Christian
+6  A: 

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 ...

ChristopheD
You could actually just do something alone the lines of $unit = $units[log($n)]
n3rd
Great Find! Thanks!
Gary Willoughby
+1  A: 

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>";
}
John Rasch
Thanks .
Gary Willoughby