Formatting human readable numbers with PHP

ript>
One of my former colleagues, Athanassios Bakalidis, in his latest blog post “Java: Formatting a Number Using a Custom Format“, has written about number formatting in Java language. This post made me think about the ways we ‘re using to print numbers from PHP to HTML output.

When we ‘re dealing with integers, usually it’s sufficient to add a

style=”text-align: right;”

to right-align the numbers in a column.

Floating point numbers, on the other hand, may require the use of number_format() function to properly format them, for example to have the same number of decimals (added to the obvious round(), floor() and ceil() functions).

But, what if I wanted to sort an array having two arithmetic columns?
Then, I’d use the sprintf() function to zero-pad numeric values, like this (certain sections are omitted):

$u0 = mysql_query( $sql, $db) or die( mysql_error());
$aa = array();
while ($u1 = mysql_fetch_row( $u0)) {
    $id = $u1[0];
    $c1 = $u1[1];
    $aa[$id] = number_format($u1[2]/$c1,4) .":". sprintf("%06d", $c1);
}
arsort( $aa); reset( $aa);
while (list($k, $v) = each($aa)) {
    list( $v1, $c1) = explode( ":", $v);
    $c1 = intval( $c1);
    $v1 = round( $v1, 2);
    [......]
}

With this technique, one can sort numeric values properly as numbers (although by internally converting them to strings).


Visit The Light of the LAMP blog for more…

One Reply to “Formatting human readable numbers with PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *

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