get float value array - php

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']);

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);

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.

Related

Format number as currency

I am (learning) using PHP to select column data from MySQL into an array using this, CONCAT('$',FORMAT(price, '5')) as price and it outputs $1,751.60000 or $10.00230 or $7.23000 which is great.
However, I would like to remove the trailing zeros but still be able to have a minimum of two decimal places
$1,751.60000 = $1,751.60
$10.00230 = $10.0023
$7.23000 = $7.23
I have read a number of similar post regarding number to currency conversion but none doesn't seem to solve my problem as they remove all the trailing zeros.
We will implement this in two way.(Mysql, PHP).
MYSQL:
FORMAT('price', 2 ) This is mysql function. It takes first parameter as value & second parameter is the number of decimal places.
Syntax:
FORMAT( value, Decimal );
Example:
FORMAT('1751.60000', 2 ) => 1751.60 // Output
FORMAT('1751.60000', 3 ) => 1751.600 // Output
PHP:
In PHP we have number_format() function. This is working same as MYSQL.
Syntax:
number_format( value, Decimal );
Example:
number_format('1751.60000', 2 ) => 1751.60 // Output
number_format('1751.60000', 3 ) => 1751.600 // Output
The Best way is to implement at MYSQL.
Note: These both function round up the values.
I will post this code in PHP since it is easier for me.
$price = $row['price']; // the original price
if (number_format($price, 2) == $price) {
echo '$'.number_format($price, 2);
} else {
echo '$'.rtrim(number_format($price, 5),'0');
}
rtrim will remove any trailing character specified. In this case, remove trailing zeros.
Note : I only put this code number_format($price, 5) because of the sample of the question. If you wish to keep all decimal number minus trailing zeros, just using $price is enough.

PHP lowest common denomination

I am working on a payment gateway and the amount parameter needs to formatted this way:
amount – (digits only) the integer value of the transaction in lowest common denomination (ex. $5.20 is 520)
I have already removed the $ and all values will be rounded to 2 decimal places.
In PHP if i try to cast amount as int ie (int)$amount I am going to loose the .20 in the example though its needed. What could be the best way to go about this?
You can multiply the amount by 100 and then convert it...
$amount = (int)($amount*100);
So 5.20 becomes 520.
If you are not sure about the number of decimal places, you could use regex to strip non-digital values from your string.
echo preg_replace('~\D+~', '', $amount);
\D means any non-numeric character. + means one or more.
If the value needs to be cast as an integer (rather than a string) write(int) just before preg_replace.
Of course, you could use str_replace() and target known characters like: $ and . (and - if it may exist).
After some feedback from the OP...
You can round and format in one step with number_format().
Code: ( Demo: https://3v4l.org/ir54s )
$amounts = array(0.001, 0.005, 5.20, 5.195, 5.204, 5);
foreach ($amounts as $amount) {
echo $amount , "->" , (int)number_format($amount, 2, '', '')."\n";
}
Output:
0.001->0
0.005->1
5.2->520
5.195->520
5.204->520
5->500

How to show decimal value after multiplication

I have value which stored in database like price. 123.00
When i tried to see the subtotal which is quantity * price.
So 123.00*1 = 123.00
But in view it shows 123 instead of 123.00 where price showing like 123.00 in same table.
How can i show decimal value after multiplication?
You need to format the number using number format PHP function. Consider
$price = 125;
$quantity = 1;
echo number_format($quantity*$price,2);
You can also have extra comma separated values that set the decimal separator, i.e. "." and the thousands separator also i.e. ",". See http://php.net/manual/en/function.number-format.php

How to calculate using a POST variable?

I need to multiply this POST variable by 12. As an example, if the amount was 10, the result should say:
Amount: 120
Here's my code so far:
Amount :'.$_POST['my_amount'].'<br/>
I tried to run the calculation in another variable, but this doesn't seem to work:
$result = ($_POST['my_amount'])*12;
or maybe it works and my output code is not working:
$vl_text='';
Amount :'.$_POST['my_amount'].'<br/>'.;
If you want your output to resemble your first example.,.. Amount:120 your missing chunks in each of the following 3 examples. first ensure that your $_POST variable is a valid one and set it to a new variable so you can print out the variable if you need to ...
// if you only expect $_POST['my_amount'] to contain integers...
if(is_int(intval($_POST['my_amount']))){
$my_amount = intval($_POST['my_amount']) * 12;
// or if you expect $_POST['my_amount'] to possibly contain a decimal
if(is_float(floatval($_POST['my_amount']))){
$my_amount = floatval($_POST['my_amount']) * 12;
intval ensures that a variable is cast as an integer if it can be, while not entirely necessary as multiplying in php will do this...its good practice to check any variables that you are using for and math functionality.
floatval does the same for for numbers with decimal. as an integer has to be a whole number if your variable could numbers that could contain decimals... use floatval
all of your examples then need to specify to print/echo the string....so
// your second line
echo 'Amount :'.$my_amount .'<br/>';
// your fourth line...
$vl_text='Amount: '.$my_amount;
echo $vl_text;
}
The most logical explanation is that you get string from POST. A good way to achieve what you want is to convert the POST value to int but keep in mind that it could not be numerical.
$int = (is_numeric($_POST['my_amount']) ? (int)$_POST['my_amount'] : 0); //If POST value is numeric then convert to int. If it's not numeric then convert it to 0
$_POST['my_amount'] = 150;
$data = $_POST['my_amount'] * 12;
echo $data;
Result will be 1800

Calculating total price from string value in php

I have a e-commerce shop and on the shopping cart page it gives me a separate price for every product, but I need total price.
in order to do that, I need to calculate all these values together and that's fine.
But, what bugs me is that I should calculate the sum of variables that are given in this format:
$455.00
What is the best way to extract the value "455" so I could add it to another value afterwards?
I hope I made myself clear...
Don't use float, but instead use an integer in cent. Floats are not precise (see Floating Point Precision), so the calculation tend to fail if you use floats. That's especially a burden if it is related to payments.
$str = '$455.00';
$r = sscanf($str, '$%d.%d', $dollar, $cent);
if ($r <> 2 or $cent > 99 or $cent < 0 or $dollar > 9999 or $dollar < 0) throw new Exception(sprintf('Invalid string "%s"', $str));
$amountInDollarCents = $dollar * 100 + $cent;
echo $str, ' -> ', $amountInDollarCents;
Demo
If you need only the dollar sign removed, use str_replace. To convert that to int or float, typecast it. However, using float results in non-exact calculations so be careful with it!
$newval = (int)str_replace('$', '', '$455.00');
I think that your ECommerce site only has $ (USD)
$price= substr($string_price,1);
This will convert your string to a float:
$price = (float)substr("$455.00", 1);
echo($price);
For more information, you can see this answer, which has a couple of good links for you in it.
What about the following:
$amount = array();
$amount[0] = '$455.15';
$amount[2] = '$85.75';
$total = 0;
foreach ($amount AS $value) {
$value = str_replace('$', '', $value);
$total += $value;
}
echo $total . "\n";
The cleaning operation is:
$value = str_replace('$', '', $value);
You might want to extract it in a function, especially if you need to use it in more than one place.
Another thing to think about is, why do you have the value in such way? It's a display format and such conversion should be the last to be done, ideally by the template. Maybe, if possible, you should consider to fix the code before, instead of applying a patch like this one.
It really looks like your program is doing it wrong. You should really represent all prices as (double) instead of a string. Then only when you need to show the price to the user you would prepend the $ sign to it, converting it to a string. But your program should really treat prices as numbers and not strings.
If you storing your price in the database as a string "$5.99" then you are really doing it wrong.
It's been a long time since I worked with PHP, so I don't know what the best practice would be for working with currency. One quick method would be to remove "$" and ".", and just add together the resulting as integers.
use str_replace() for instance, and replace "$" and "." with an empty string: http://se2.php.net/manual/en/function.str-replace.php
This will give you the whole sum in cents (thus avoiding some potential rounding problems). You can then divide it by 100 and format it however you like to display the sum as dollars.

Categories