【发布时间】:2014-06-03 15:03:47
【问题描述】:
我正在尝试使用 PHP 添加一些货币。
我要加起来的值是这样的:
- 2.500
- 10,50
- 20,70
- 15
- 75
第一个是 2000 欧元,第二个是 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;
如您所见,我正在从租金值中删除所有不是数字的内容。当然,当租金值是浮点数而不是整数时,这会导致一个主要问题。
我将如何正确计算货币? 我不知道在其他国家是怎么做的,但点代表 1000,逗号代表美分。
【问题讨论】:
-
格式至少是一致的,所以你永远不会得到
2.500 = two thousand five hundred和2.500 = two euro 50 cents?如果你这样做了,那么基本上没有办法可靠地翻译这个,因为你不能让完全相同的字符串代表两个完全不同的值。 -
美分总是被描述为
2,50,而不是2.50。2.50不会发生,但2.500可以(并且是)。