2

I have a big time trying to either convert a string into a integer or multiply two integers. I can't convert the string into integer because it's resulting me into a boolean (when I'm using var_dump). I can convert the other integer in string, but I'm unable to multiply it.

I have this:

    <? $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

    ?>

I tried converting the payfee in integer, but still can't make it work. I did something like this before and worked well, but not this time.

Any help will be appreciated.

P.S Thank you to the whole stackoverflow.com community which helped me many times before.

4

5 回答 5

5

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;

as->get_total()接收一个字符串,并->total接收一个浮点数。

于 2012-09-25T10:56:48.727 回答
3

尝试这个

$integer =(int)$string;

活生生的例子

使用 var_dump() 是正确的

在此处输入图像描述

检查这个链接

于 2012-09-25T09:37:37.083 回答
2

使用 intval() 函数将字符串转换为整数

间隔

于 2012-09-25T09:39:10.250 回答
2

使用类型转换,如

$integer = (int)$myString;

然后你可以将它转换为整数,它变得很容易相乘

于 2012-09-25T09:41:45.427 回答
0

从你小学技术的算法张贴在这里。在这种情况下,您不需要将字符串转换为整数

于 2018-12-07T16:10:04.540 回答