计算货币价值是错误的

时间:2014-06-11 08:37:59

标签: php floating-point int currency

我试图加上一些数字(金钱),但由于某种原因,输出并不是我的预期。

值为:

  • 2500.30
  • 13.50
  • 25
  • 5.40
  • 120

我期望的是2664.20,但我得到的输出是163.9。 这是我的代码:

// Get the price of the product
$rent = $product->get_price_html();
// Remove the dot and change the comma into a new dot
$rent_float = str_replace(',', '.', str_replace('.', '', $rent));

// Get the custom fields, example: 10.50 (the price)
$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);

// Change the dots into comma's to make it more readable
$gwl_comma = str_replace('.', ',', $gwl);
$tti_comma = str_replace('.', ',', $tti);
$heffing_comma = str_replace('.', ',', $heffing);
$verzekering_comma = str_replace('.', ',', $verzekering);

// Add up the values where comma's were replaced with dots
$total = $rent_float + $gwl + $tti + $heffing + $verzekering;

// Change the dot from the total into a comma to make it more readable
$total_comma = str_replace('.', ',', $total);

我删除了点并更改了rent中的逗号,因此我可以使用我从自定义字段中获取的其他值更轻松地计算它。  此外,最后的0将从最终值中删除。我在谷歌上看了这个,但只能找到与阵列相关的结果。

任何人都可以看到出了什么问题吗?

2 个答案:

答案 0 :(得分:1)

首先以某种独特的格式转换所有值。 例如

  

####.##

将<{1}}用于此

稍后您不需要删除点,因为php可以使用变量类型轻松调整而不声明

所以当你拥有所有的价值时:

number_format($var, 2)

现在总结所有这些并检查

答案 1 :(得分:0)

你为什么这么挣扎。

你在顶部做得很好。你只需要像处理租金一样赚取所有金额相同的流程。

$rent = $product->get_price_html();
$rent_float = str_replace(',', '.', str_replace('.', '', $rent));

$gwl = get_post_meta( $post->ID, 'g/w/l_prijs', true);
$gwl_float = str_replace(',', '.', str_replace('.', '', $gwl));

$tti = get_post_meta( $post->ID, 't/t/i_prijs', true);
$tti_float = str_replace(',', '.', str_replace('.', '', $tti));

依旧......

然后最后添加所有浮点值

$total = $rent_float + $gwl_float + $tti_float + $heffing_float + $verzekering_float;

就是这样。

:)尽情享受!