PHP:如何使用number_format添加俄罗斯卢布

时间:2015-11-25 13:49:16

标签: php

我正在开发购物车并使用以下数字格式显示俄罗斯卢布:

number_format($price, 0, ',', ' ');//Example 15 525 instead of 15525

现在,当我添加小计与运费成本
例如:

小计:61 305
发货:8 250

我得到以下结果

69而不是69 555

如何使用上面的数字格式正确添加它们?

2 个答案:

答案 0 :(得分:0)

看起来您正在修改价格值以在尝试将它们添加到一起之前更改其显示。如果您的代码如下所示:

$subtotal = number_format($price, 0, ',', ' ');         // 61 305
$shipping = number_format($shipping_cost, 0, ',', ' '); // 8 250

$total = $subtotal + $shipping;            // $total = "61 305" + "8 250" = 61 + 8 = 69

然后PHP将格式化数字转换为小数,这意味着在空格之后删除所有内容。

最好的解决方案是更改$ total变量,以便在格式化之前添加变量,而不是之后。

答案 1 :(得分:0)

您应该事先将这些值一起添加:

$subtotal = 61305;
$shipping = 8250;
$total = $subtotal + $shipping;

使用money_format()正确格式化

setlocale(LC_MONETARY, 'ru_RU');
echo money_format('%i', $total) . "\n";

输出是:

69 555,00 RUB