I'm developing a table with two columns, "State" and "Sales". To get the number in the sales column, I use the wc_price function, which works just fine to output a currency string:
CA $1,652.13
CO $515.80
...etc.
I have at least 50 rows, one for each state.
The very last row will output the total of all the dollar amounts from column 2.
I discovered that the actual result from wc_price isn't just a sting, it's a block of html:
<bdi>
<span >$</span>
435.50
</bdi>
I tried to get to the actual number within the html, 435.50
using strip_tags:
$numeric = strip_tags(wc_price($total)); // result is a simple string, with the $ sign
echo str_replace("$","",$numeric) . "<br>"; // doesn't strip away the $ sign.
$tally = $tally $numeric; // produces an error, non-numeric value.
The error is on the $tally =
line. This doesn't work in any way. Sure, the html tags are stripped, and I'm left with a string: $435.50
. In other words, I can't get rid of that danged '$' for some reason. I simply cannot parse, convert, or anything to that currency string. (int), intval($numeric), (float)$numeric, floatval($numeric), etc., none of these work. number_format doesn't work, either.
Warning: A non-numeric value encountered in C:\xampp\htdocs\mysite\wp-content\plugins\my-custom-plugin\my-custom-plugin.php on line 104
CodePudding user response:
Add a floatval()
around your str_replace
and assign the variable.
$numeric = strip_tags($html);
$numeric = floatval(str_replace("$", "", $numeric));
See working example. It works with 5.6, 7.4 and 8.1.
CodePudding user response:
I'm not sure of the result, but I think it's possible to have the price without the currecy reading from the documentation of wp_price:
$numeric = wp_price($total, array('currency'=>''));
However you can have some action that change the comportament of the wc_price function.