将数字格式设置为货币

时间:2018-07-25 03:48:26

标签: php mysql

我正在(学习)使用PHP,使用CONCAT('$',FORMAT(price, '5')) as price从MySQL将列数据选择到数组中,它输出$ 1,751.60000或$ 10.00230或$ 7.23000,这很棒。

但是,我想删除尾随的零,但仍然能够保持最少两个小数位

$ 1,751.60000 = $ 1,751.60

$ 10.00230 = $ 10.0023

$ 7.23000 = $ 7.23

我读过许多关于数字到货币转换的类似文章,但是似乎没有一个解决我的问题的,因为它们删除了所有结尾的零。

2 个答案:

答案 0 :(得分:1)

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

MYSQL:

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

语法:

FORMAT( value, Decimal );

示例:

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

PHP:

在PHP中,我们具有number_format()函数。这与MYSQL相同。

语法:

number_format( value, Decimal );

示例:

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

最好的方法是在MYSQL上实现。

注意:这两个功能均会取整值。

答案 1 :(得分:0)

我将用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_format($price, 5)。如果您希望保留所有十进制数减去尾随零,只需使用$price就足够了。