0

I'm a newbie in PHP, and for a woocommerce I'm trying to multiply a price by 2.

$priceOriginal = WC()->cart->get_cart_subtotal(); // return 450,00€
$priceNoCur  = preg_replace( '/&.*?;/', '', $priceOriginal );  // return 450,00
$priceNoCurDot = preg_replace( '/,/', '.', $priceNoCur);  // return 450.00
$priceFinalDot = floatval($priceNoCurDot) * 2;
echo $priceFinalDot;   // return 0

I found how to delete de euro sign and change the coma by a dot, but when I multiply by two my result is 0 … why !?

SOLUTION

I find a other way to call the price : $priceOriginal = WC()->cart->total; then I was able to multiply this number as a normal calculation.

Alex
  • 81
  • 1
  • 10

1 Answers1

2

Your priceOriginal is not what telling, if I assume it is some thing like "450,00€" then I must return 900 when you multiple it by 2. try to var_dump($priceOriginal); before doing any further operation

$priceOriginal = "450,00€";
$priceNoCur  = preg_replace( '/&.*?;/', '', $priceOriginal );  // return 450,00
$priceNoCurDot = preg_replace( '/,/', '.', $priceNoCur);  // return 450.00
$priceFinalDot = floatval($priceNoCurDot) * 2;
echo $priceFinalDot;   // returns 900

For debug:

$priceOriginal = WC()->cart->get_cart_subtotal();
var_dump($priceOriginal); //see what you get 

As per your comment, If it is returning string(119) "450,00€",then you should trim your $priceOriginal variable like $priceOriginal = trim(WC()->cart->get_cart_subtotal()); before doing further operation because It may have some extra space characters.

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • Hey thanks for your help. It returns string(119) "450,00€" … – Alex Oct 19 '17 at 15:58
  • but if it is only `450,00€` then it should return `string(9) "450,00€" ` not string(**119**), I think you need `trim()` if you've other spaces with your money string.. – A l w a y s S u n n y Oct 19 '17 at 16:06
  • @Alex See my edit and let me know whether it is working or no? – A l w a y s S u n n y Oct 19 '17 at 16:11
  • So I do $priceOriginal = trim(WC()->cart->get_cart_subtotal()); var_dump($priceOriginal); and still return string(119) "450,00€" – Alex Oct 19 '17 at 16:16
  • Then your $priceOriginal contains non-printable characters. Check out this link https://stackoverflow.com/questions/28102962/why-would-var-dump-return-a-bigger-value-than-the-string-length?answertab=active#tab-top – A l w a y s S u n n y Oct 19 '17 at 16:26
  • I finally found a other way to call the price : $priceOriginal = WC()->cart->total; then I was able to multiply this number as a normal calculation. Thanks for your help – Alex Oct 19 '17 at 16:46