user10431773
user10431773

Reputation:

get float value array

How can i get the float value of the string in the array ? I need it in the invoice.

foreach( $this->get_woocommerce_totals() as $key => $total ) :

        if($total['label']==="Subtotal") $subtotal = $total['value'];

endforeach;

print_r($total);

Array ( [label] => Subtotal [value] => 8.144 lei )

I have tried but it did not help

$subtotal = (float)$total['value']; 
$subtotal = floatval($total['value']);

Upvotes: 0

Views: 142

Answers (2)

nico gawenda
nico gawenda

Reputation: 3748

Both (float) and floatval() should work. If for some reason they do not, a simpler solution than regexp is this one liner:

$price = '8.144 lei';
echo floatval(explode(' ', $price)[0]);

It is preferable to regexp, because it also works with 8.144, 8.144 abc def more spaces, and even with an empty string (returns 0).

However, this is a trivial thing which you can expect to be a part of WooCommerce - probably there is another function that returns the value you need.

According to the docs there indeed are specific functions for every need:

WC_Cart::get_cart_contents_total() – Gets cart total. This is the total of items in the cart, but after discounts. Subtotal is before discounts.
WC_Cart::get_shipping_total() – Get shipping_total.
WC_Cart::get_cart_subtotal(); - Gets the sub total (after calculation). **-> string, formatted price - not what you want**
WC_Cart::get_subtotal_tax() – Get subtotal.
WC_Cart::get_subtotal() – Get subtotal. **-> float, you are looking for that?**
WC_Cart::get_taxes_total() – Get tax row amounts with or without compound taxes includes.
wc_price() – Format the price with a currency symbol.

Unfortunately, the docs are not clear on which of these take taxes into account, so you'd need to try and check. At least from a logical perspective, get_subtotal()should be your thing.

Upvotes: 0

Ro Achterberg
Ro Achterberg

Reputation: 2714

Here's one way of doing it. See comments for step-by-step explanation.

<?php

// $total['value']
$value = '8.144 lei';

// Regex explanation:
// ^ -- Start at beginning of input
// ( -- Start capture
// [\d\.] -- Allow all digits and/or a period.
// + -- Need one or more of character set.
// ) -- End capture

// preg_match() accepts in its third argument an array that will
// hold all matches made. The value you're after will be stored
// at index 1.
if (preg_match('/^([\d\.]+)/', $value, $matches) === 1)
    // Explicitly cast the captured string to a float.
    $floatVal = (float)$matches[1];
else
    die('Bad regex or no match made.');

// Outputs: float(8.144)
var_dump($floatVal);

Upvotes: 1

Related Questions