PHP整数格式的数字格式化

3
我会使用PHPnumber_format函数来表达商品价格,包括小数点、千位分隔符等。例如:
$price = 20.456;
print "$" . number_format($price, 2, ".", ",");

输出结果为$20.46

如果价格为整数,例如$price = 20.00,我希望输出$20。有没有其他函数或规则可以实现这一点,避免不必要的小数点?


我选择了billyonecan的解决方案,因为它非常优雅。我原以为这个函数本身可能有一个参数来“尊重”整数,但事实并非如此,使用if-else比较就足够了,而且用三元形式表达非常优雅。 - Cesar
6个回答

8

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

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

3
尝试使用$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)转换为浮点数,但我觉得这更简单。


但这不是期望的结果,只有在价格为整数时才应删除尾随零。 - billyonecan
@billyonecan 你可以尝试使用 echo 1000000 + 0; // 1000000 - Mohammad Fareed
echo 966.70 + 0; // 966.7期望的结果是:966.70 - billyonecan
是的,正确。在执行+0操作之前,我们必须编写一个函数。感谢您的建议,您有任何解决方案吗? - Mohammad Fareed

3
你可以使用三目运算符来实现这个:
    $price = 20.456;
    print "$" . ($price == intval($price) ? number_format($price, 0, "", ",") : number_format($price, 2, "", ","));

2
一个小的辅助函数my_format用来确定数字是否为整数,然后返回相应的字符串。
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);

Will output

$20.46 $20


2
一个适用于任意数字的小解决方案
$price = "20.5498";
$dec = fmod($price, 1);
if($dec > 0)
    print "$" . number_format($price, 2, ".", ",");
else
    print "$" . floor($price);;

0

你可以使用 floor() 函数

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接