PHP 数字格式与整数格式

PHP number format with integer format

我是用PHPnumber_format来表示产品的价格,使用小数点,千位分隔符等。例如:

$price = 20.456;
print "$" . number_format($price, 2, ".", ",");

输出.46.

但是,如果价格是整数,例如 $price = 20.00,我希望输出 。是否有其他一些功能或规则可以实现此目的,如果不需要则避免使用小数点?

尝试$price = 20.456 +0 ;

$price + 0 does the trick.

echo  125.00 + 0; // 125
echo '125.00' + 0; // 125
echo 966.70 + 0; // 966.7

在内部,这相当于使用 (float)$price 或 floatval( $price) 强制转换为浮动,但我发现它更简单。

您可以为此使用三元运算符:

    $price = 20.456;
    print "$" . ($price == intval($price) ? number_format($price, 0, "", ",") : number_format($price, 2, "", ","));

您可以使用floor()函数

$price = 20.456;
echo '$'.floor($price); // output 

一个小辅助函数 my_format 判断数字是否为整数然后 return 相应的字符串。

function my_format($number)
{
    if (fmod($number, 1) == 0) {
        return sprintf("$%d\n", $number);
    } else {
        return sprintf("$%.2f\n", $number);
    }
}

$price = 20.456;

echo my_format($price);
echo my_format(20);

会输出

.46

适用于任何数字的小解决方案

$price = "20.5498";
$dec = fmod($price, 1);
if($dec > 0)
    print "$" . number_format($price, 2, ".", ",");
else
    print "$" . floor($price);;

只需将 $price 转换为整数与 $price 进行松散比较,如果它们匹配(即它是一个整数),您可以格式化为 0 位小数:

number_format($price, ((int) $price == $price ? 0 : 2), '.', ',');