【问题标题】:Adding up currency values添加货币价值
【发布时间】: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 可以(并且是)。

标签: php currency


【解决方案1】:

您似乎正在使用 Woocommerce。

如果我没记错的话你应该可以做到:

$rent = $product->get_price();

然后摆脱所有 preg_replace 废话。

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

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

【讨论】:

    【解决方案2】:

    如果您想将逗号用作小数,则不能将其去掉。

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-11-03
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多