开发者

PHP Currency formatting trailing zeros

开发者 https://www.devze.com 2023-02-10 16:17 出处:网络
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?

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?

Th开发者_如何学Canks! :)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号