简体   繁体   中英

PHP Currency formatting trailing zeros

Is it possible to have PHP format currency values, for example: $200 will output as: $200 (without decimals) but with a number like $200.50 it will correctly output $200.50 instead of $200.5?

Thanks! :)

$num_decimals = (intval($amt) == $amt) ? 0 :2;
print ("$".number_format($amt,$num_decimals);

If you don't mind handling the currency on your own, you can simply use the following on the number, to get the correct output.

This solution will always output trailing zeros (xx.x0 or xx.00 depending on the provided number)

$number = 1234
sprintf("%0.2f",$number);
// 1234.00

How about a custom function to handle the situation accordingly:

function my_number_format($number) {
    if(strpos($number, '.')) {
        return number_format($number, 2);
    } else {
        return $number;
    }
}

you can use number_format to do this.

Example:

$Amount = 200.00;
echo "$" . number_format($Amount); //$200

There are a couple of ways. Probably the most universally supported and recommended method is sprintf.

sprintf("%01.2f", "200.5"); //200.50
sprintf("%01.2f", "10"); //10.00

number_format is good as well, and has all sorts of options, and it will add thousands separators and such if requested to do so.

There's also a money_format function, but it is unsupported on Windows servers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM