问题:将字符串转换为整数并将两个整数相乘

我有很多时间尝试将字符串转换为整数或将两个整数相乘。我无法将字符串转换为整数,因为它导致我变成布尔值(当我使用 var_dump 时)。我可以转换字符串中的另一个整数,但我无法将它相乘。

我有这个:

    <? $fees=$commerce->cart->get_total(); 
    $payfee = str_replace('&nbsp;&euro;', '', $fees);
    $payfee = str_replace(',','', $payfee);  //this is the string
    $fee = 0.025;
    $paypal = $payfee * $fee;  //this thing is not working

    ?>

我尝试将payfee转换为整数,但仍然无法正常工作。我以前做过这样的事情并且效果很好,但这次不行。

任何帮助将不胜感激。

P.S 感谢整个 stackoverflow.com 社区,他们之前曾多次帮助过我。

解答

OP 正在运行 WooCommerce,他的$commerce->cart->get_total();函数响应输出,例如<span class="amount">560&nbsp;&euro;</span>(560 欧元),他询问如何将其转换为数字,以便从金额中收取费用(2.5%)。

首先这里的问题是get_total()函数响应的是一个字符串。

修复此字符串的正确方法是一个简单的示例,例如

<?php
    $totalAmountString = $commerce->cart->get_total(); //<span class="amount">560&nbsp;&euro;</span>
    $totalAmountString = strip_tags($totalAmountString); //get rid of the span - we're left with "560&nbsp;&euro;"
    $totalAmountString = str_replace(array("&nbsp;&euro;", ","), "", $totalAmountString);
    $totalAmountFloat = (float)$totalAmountString;
    $fee = 0.025;
    $feeForThisAmount = $totalAmountFloat * $fee;
    var_dump($feeForThisAmount);

    $totalAmountWithFee = $totalAmountFloat + $feeForThisAmount;
    var_dump($totalAmountWithFee);
?>

但是,根据Woo Commerce API 文档您应该能够使用$commerce->cart->total来获取数字的浮点数,因此_可能_也可以使用的解决方案(同样,我对 WooCommerce 一无所知)如下:

<?php
    $totalAmountFloat = $commerce->cart->total;
    $fee = 0.025;
    $feeForThisAmount = $totalAmountFloat * $fee;
    var_dump($feeForThisAmount);

    $totalAmountWithFee = $totalAmountFloat + $feeForThisAmount;
    var_dump($totalAmountWithFee);
?>

编辑

根据您最新的数据转储,问题是您正在使用

$paypal_fees=$woocommerce->cart->get_total() * 0.025;

你应该在哪里使用

$paypal_fees=$woocommerce->cart->total * 0.025;

因为->get_total()接收一个字符串,而->total接收一个浮点数。

Logo

WooCommerce社区为您提供最前沿的新闻资讯和知识内容

更多推荐