I am trying to improve a woocommerce plugin to add an additional field in a report.
A value of $25.80 is displayed via the variable $item[‘order_price’]
What I am trying to do is convert the value to a number of 25.80 so that I can run a calculation with it. I have tried numerous methods all of which have been unsuccessful (see below).
When I run the following code var_dump($item[‘order_price’])
it returns the following string(128) "$25.80"
Any ideas how I can convert this to a number for calculating?
Thanks in advance
# Returns 0
<?php echo intval($item['order_price']); ?>
# Returns 0
<?php echo (int)$item['order_price']; ?>
# Returns 0
<?php echo( intval($item['order_price'])); ?>
# Returns 0
<?php $item_price = ( Number($item['order_price'])); ?>
# Return 200 OK
<?php $unit_price = ereg_replace("[^0-9]", "", $item['order_price']); ?>
# Returns $25.80
strval($item['order_price']);
# Retuns 0
<?php echo floatval($item['order_price']); ?>
# Retuns 1
<?php echo settype($item['order_price'], integer); ?>
# Retuns True
<?php echo (boolval($item['order_price']) ? 'true' : 'false')."n"; ?>
# Returns String
<?php echo "order price -".gettype($item['order_price']); ?>
# Retuns False
<?php var_dump(is_float($item['order_price'])); ?>
# Retuns $25.801
<?php echo print_r($item['order_price']); ?>
# Retuns 128
<?php echo strlen($item['order_price']); ?>
# Reurns Null
<?php echo substr($item, 0, 5); ?>
# Reurns Null
<?php echo mb_substr($item, 0, 5); ?>
3
Answers
After some work I finally managed to resolve this issue with Jerry pointing me in the right direction.
The string containing the value had multiple characters to deal with and when left with only numbers I notice extra numbers that should not have been there that had been added by the developer to prevent editing the string easily.
Final result looks like this
It’s the
$
that’s messing you up. Trytrim($item['order_price'], '$')
and turn that into a float.Edit to add: you could also use
substr
or a few other methods to remove the$
, but the above states very nicely your intent, which means the next person will understand instantly what that line of code is there to to.Edit again to add: The
trim
function does not alter the provided string, it returns a new, trimmed string.please see https://www.php.net/manual/en/function.trim.php
As an alternative approach, please consider using
NumberFormatter
to both parse the currency to a float value and output the float value in the desired currency.Example: https://3v4l.org/XmE3h
Result
Although
string(128) "$25.80"
does not make sense, perhaps there is additional hidden characters in the variable? If it is just white-space, usetrim($item['order_price'])