Php 将数字格式化为货币

Php 将数字格式化为货币,php,mysql,Php,Mysql,我正在(学习)使用PHP将MySQL中的列数据选择到一个数组中,使用这个,CONCAT(“$”,FORMAT(price,'5'))作为price,它输出1751.60000美元或10.00230美元或7.23000美元,这非常好 但是,我希望删除尾随的零,但仍然能够有两个小数位的最小值 1751.60000美元=1751.60美元 $10.00230=$10.0023 $7.23000=$7.23 我读过很多类似的关于数字到货币转换的帖子,但是没有一篇能够解决我的问题,因为它们删除了所有尾随的

我正在(学习)使用PHP将MySQL中的列数据选择到一个数组中,使用这个,
CONCAT(“$”,FORMAT(price,'5'))作为price
,它输出1751.60000美元或10.00230美元或7.23000美元,这非常好

但是,我希望删除尾随的零,但仍然能够有两个小数位的最小值

1751.60000美元=1751.60美元

$10.00230=$10.0023

$7.23000=$7.23


我读过很多类似的关于数字到货币转换的帖子,但是没有一篇能够解决我的问题,因为它们删除了所有尾随的零。

我将用PHP发布这段代码,因为这对我来说更容易

$price = $row['price']; // the original price
if (number_format($price, 2) == $price) {
    echo '$'.number_format($price, 2);
} else {
    echo '$'.rtrim(number_format($price, 5),'0');
}
rtrim
将删除指定的任何尾随字符。在这种情况下,删除尾随的零


注意:由于问题的样本,我只将此代码
number\u格式($price,5)
。如果您希望保留所有十进制数减去尾随零,只需使用
$price
就足够了。

我们将以两种方式实现这一点。(Mysql、PHP)

MYSQL:

FORMAT('price',2)
这是mysql函数。它将第一个参数作为值,第二个参数是小数位数

语法:

FORMAT( value, Decimal );
number_format( value, Decimal );
例如:

FORMAT('1751.60000', 2 ) => 1751.60 // Output
FORMAT('1751.60000', 3 ) => 1751.600 // Output
number_format('1751.60000', 2 ) => 1751.60 // Output
number_format('1751.60000', 3 ) => 1751.600 // Output
PHP:

在PHP中,我们有number_format()函数。这与MYSQL的工作原理相同

语法:

FORMAT( value, Decimal );
number_format( value, Decimal );
例如:

FORMAT('1751.60000', 2 ) => 1751.60 // Output
FORMAT('1751.60000', 3 ) => 1751.600 // Output
number_format('1751.60000', 2 ) => 1751.60 // Output
number_format('1751.60000', 3 ) => 1751.600 // Output
最好的方法是在MYSQL上实现


注意:这两个函数都会对值进行取整。

您希望仅使用SQL还是使用PHP解决此问题?这并不能解决问题。1.23456将四舍五入到1.23,这不是OP想要的。请参阅,这将不起作用,因为$number_format()希望参数1为浮点,字符串给定。为什么我的代码不起作用?我对它进行了测试,结果如预期的那样:$row['price']使用了什么?该值是数据库中的原始值。如果$row['price']带有“$”,则此代码将不会像number_format()所预期的那样工作。