加上货币值

时间:2014-06-03 15:03:47

标签: php currency

我正在尝试使用PHP添加一些货币。

我想要加起来的值是这样的:

  • 2.500
  • 10,50
  • 20,70
  • 15
  • 75

第一个是2千欧元,第二个是10欧元和50美分。

我想加上这些,所以它总计达到2621,20欧元(如果我正确计算的话)。

我尝试将值传递给浮点数,但这并没有给出我预期的结果。 这是我到目前为止所做的:

$rent = $product->get_price_html();
$rent_int = (int) preg_replace('|[^0-9]|i', '', $rent);

// I'm working in wordpress, but the values are the same as the above ones

$gwl = get_post_meta( $post->ID, 'g/w/l_prijs', true);
$tti = get_post_meta( $post->ID, 't/t/i_prijs', true);
$heffing = get_post_meta( $post->ID, 'heffingen_prijs', true);
$verzekering = get_post_meta( $post->ID, 'verzekering_prijs', true);

$total = (float)$rent_int + (float)$gwl + (float)$tti + (float)$heffing + (float)$verzekering;

正如你所看到的那样,我正在从租金价值中删除所有不是数字的东西。当然,当租金值是浮动而不是int时,这会引起一个重大问题。

我如何正确计算货币? 我不确定它是如何在其他国家完成的,但是点代表1000而逗号是美分。

2 个答案:

答案 0 :(得分:1)

您似乎正在使用Woocommerce。

如果我没有记错,你是否应该这样做:

$rent = $product->get_price();

然后摆脱所有preg_replace无意义。

这应该将$ rent设置为您可以进行数学运算的浮点值。

http://docs.woothemes.com/wc-apidocs/source-class-WC_Product.html#752-759

答案 1 :(得分:0)

如果您想将逗号用作小数,则无法将其删除。

尝试使用此行而不是当前行来获取$rent_int

$rent_int = (float) str_replace(',','.',preg_replace('|[^0-9,]|i', '', $rent));

显然这不再是一个int(它是一个浮点数),但我会把你的变量名称整理给你。

相关问题