Printing money with PHP

Filed under: PHP | 1 Comment

I recently (a few minutes ago) had to output human readable values for money with PHP. While PHP may love to work with values like “10.5”, humans like to read “$10.50”. We also round money to 2 decimal places unless gas is for sale and the extra 9/10 cent is added in to trick the customers. There is probably a built-in function that does this, but I couldn’t find it. And as you can see, the solution is really short:


function makeMoney ($value) {

$value = round($value, "2");

if (ereg("^([0-9]*\.[0-9])$", $value)) {
$value = $value . "0";
} else if (ereg("^([0-9]*)$", $value)) {
$value = $value . ".00";
}

$value = "$" . $value;
return $value;
}

Read on for examples.

Example usage:

include('functions.php');
$total = "10.4";
echo makeMoney($total);

Outputs:

$10.40

We can also do slick things like:


";
}
?>

Outputs:

10.5 x 10.5 = $110.25
10 x 10 = $100.00
10.31 x 10.31 = $106.30
10.5 x 10.5 = $110.25
10.00 x 10.00 = $100.00
315.252 x 315.252 = $99383.82

Why’s this handy? You can keep your machine readable numbers for later use, but output them nicely for people. No need for extra variables either, you can call the function from within an echo() statement.

If you have any tips or know of the built in function that does this (there HAS to be one!), let me know.

Read the latest posts

One Response to “Printing money with PHP”

  1. jacob says:

    in php 4.3 there is a money_format function
    http://us4.php.net/money-format

    Heres one we threw together …
    function makeMoney($value){
    return ‘$’.number_format($value, 2, ‘.’, ‘,’)
    }

    It also adds commas for larger amounts of money

    ex. makeMoney(99383.82) returns $99,383.82

Leave a Reply