Convert string to integer and multiply two integers - php

I have a big time trying to either convert a string into a integer or multiply two integers. I can't convert the string into integer because it's resulting me into a boolean (when I'm using var_dump). I can convert the other integer in string, but I'm unable to multiply it.
I have this:
<? $fees=$commerce->cart->get_total();
$payfee = str_replace(' €', '', $fees);
$payfee = str_replace(',','', $payfee); //this is the string
$fee = 0.025;
$paypal = $payfee * $fee; //this thing is not working
?>
I tried converting the payfee in integer, but still can't make it work. I did something like this before and worked well, but not this time.
Any help will be appreciated.
P.S Thank you to the whole stackoverflow.com community which helped me many times before.

OP is running WooCommerce, and his $commerce->cart->get_total();
function responds output such as <span class="amount">560 €</span> (560 €)
and he's asking how to convert this to a number so he can get a fee
(2.5 %) from the amount.
First of all, the problem here is that the get_total() function responds with a string.
The correct way to fix this string would be a simple example such as
<?php
$totalAmountString = $commerce->cart->get_total(); //<span class="amount">560 €</span>
$totalAmountString = strip_tags($totalAmountString); //get rid of the span - we're left with "560 €"
$totalAmountString = str_replace(array(" €", ","), "", $totalAmountString);
$totalAmountFloat = (float)$totalAmountString;
$fee = 0.025;
$feeForThisAmount = $totalAmountFloat * $fee;
var_dump($feeForThisAmount);
$totalAmountWithFee = $totalAmountFloat + $feeForThisAmount;
var_dump($totalAmountWithFee);
?>
However, according to the Woo Commerce API Documentation you should be able to use $commerce->cart->total to get a float of the number, so a solution that might also work (again, I know nothing about WooCommerce), would be the following:
<?php
$totalAmountFloat = $commerce->cart->total;
$fee = 0.025;
$feeForThisAmount = $totalAmountFloat * $fee;
var_dump($feeForThisAmount);
$totalAmountWithFee = $totalAmountFloat + $feeForThisAmount;
var_dump($totalAmountWithFee);
?>
Edit
According to your latest data dump, the problem is that you're using
$paypal_fees=$woocommerce->cart->get_total() * 0.025;
where you should be using
$paypal_fees=$woocommerce->cart->total * 0.025;
as ->get_total() receives a string, and ->total receives a float.

try this
$integer =(int)$string;
LIve example
with var_dump() its correct
check this link

Use type casting like
$integer = (int)$myString;
then you can convert it to an integer,and its become easy to multiply

Use intval() function to covert string to integer
intval

From your elementary school technique based algorithm is posted here . You need not to convert string to integer in this case

Related

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

PHP: string with decimals strips decimals when converting to float

With the function floatval() I try to convert a string with decimals to a float, but it doesn´t give me the desired result. Here´s the code:
$price_calc = str_replace(',','.',$price);
$reduction_calc = str_replace(',','',$reduction);
$reduction_calc = '1.'.$reduction;
$price_calc = floatval($price_calc);
$reduction_calc = floatval($reduction_calc);
$oldprice = $price_calc * $reduction_calc;
This chunk of code is from a scraper I´m building that fetches the price ($price) and the percentage of reduction($reduction). From that price and reduction I´m trying to calculate the old price.
Before being able to make the calculation I have to convert both $price and $reduction to float. That´s where it goes wrong
The problem is that for example when $reduction is 51 for example, the value $reduction_calc should be 1.51 . For some weird reason after applying the floatval() the variable $reduction_calc turns into 1.
Anybody out there who has an idea why? Thanks in advance!
Try this:
$reduction_calc = floatval($reduction_calc);
You probably have leading/trailing spaces in your $reduction or $price strings
Add this code before your script
$reduction = trim($reduction);
$price = trim($price);

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.

number_format in a number_format doesn't work

I'm having trouble with a tiny code in php:
$price = 135;
$price_sale = number_format($price * 0.75,2,',','');
//*returns 101,25 *//
$count_products = 3;
$new_price = number_format($price_sale * $count_products,2,',','');
//* returns 303,00 and not 303,75 *//
How can I fix this problem?
Regards,
Frank
Keep numbers as numbers. Don't format until the output stage.
Never do number_format on numbers you want to do calculations with.
101,25 is not a valid number in PHP.
Work with the raw values until the number is output. Then, do a number_format().
use:
$new_price = number_format($price * 0.75 * $count_products,2,',','');
as $price_sale is a string and won't probably have the value you're calculating with, after type casting. (See: http://php.net/manual/de/language.types.type-juggling.php)

PHP String to Float

I am not familiar with PHP at all and had a quick question.
I have 2 variables pricePerUnit and InvoicedUnits. Here's the code that is setting these to values:
$InvoicedUnits = ((string) $InvoiceLineItem->InvoicedUnits);
$pricePerUnit = ((string) $InvoiceLineItem->PricePerUnit);
If I output this, I get the correct values. Lets say 5000 invoiced units and 1.00 for price.
Now, I need to show the total amount spent. When I multiply these two together it doesn't work (as expected, these are strings).
But I have no clue how to parse/cast/convert variables in PHP.
What should I do?
$rootbeer = (float) $InvoicedUnits;
Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.
You want the non-locale-aware floatval function:
float floatval ( mixed $var ) - Gets the float value of a string.
Example:
$string = '122.34343The';
$float = floatval($string);
echo $float; // 122.34343
Well, if user write 1,00,000 then floatvar will show error. So -
floatval(preg_replace("/[^-0-9\.]/","",$input));
This is much more reliable.
Usage :
$input = '1,03,24,23,434,500.6798633 this';
echo floatval(preg_replace("/[^-0-9\.]/","",$input));
Dealing with markup in floats is a non trivial task. In the English/American notation you format one thousand plus 46*10-2:
1,000.46
But in Germany you would change comma and point:
1.000,46
This makes it really hard guessing the right number in multi-language applications.
I strongly suggest using Zend_Measure of the Zend Framework for this task. This component will parse the string to a float by the users language.
you can follow this link to know more about How to convert a string/number into number/float/decimal in PHP.
HERE IS WHAT THIS LINK SAYS...
Method 1: Using number_format() Function. The number_format() function is used to convert a string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure.
$num = "1000.314";
//Convert string in number using
//number_format(), function
echo number_format($num), "\n";
//Convert string in number using
//number_format(), function
echo number_format($num, 2);
Method 2: Using type casting: Typecasting can directly convert a string into a float, double, or integer primitive type. This is the best way to convert a string into a number without any function.
// Number in string format
$num = "1000.314";
// Type cast using int
echo (int)$num, "\n";
// Type cast using float
echo (float)$num, "\n";
// Type cast using double
echo (double)$num;
Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively.
// Number in string format
$num = "1000.314";
// intval() function to convert
// string into integer
echo intval($num), "\n";
// floatval() function to convert
// string to float
echo floatval($num);
Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly.
// Number into string format
$num = "1000.314";
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0, "\n";
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0.0, "\n";
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0.1;
Use this function to cast a float value from any kind of text style:
function parseFloat($value) {
return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,3}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}
This solution is not dependant on any locale settings. Thus for user input users can type float values in any way they like. This is really helpful e.g. when you have a project wich is in english only but people all over the world are using it and might not have in mind that the project wants a dot instead of a comma for float values.
You could throw javascript in the mix and fetch the browsers default settings but still many people set these values to english but still typing 1,25 instead of 1.25 (especially but not limited to the translation industry, research and IT)
I was running in to a problem with the standard way to do this:
$string = "one";
$float = (float)$string;
echo $float; : ( Prints 0 )
If there isn't a valid number, the parser shouldn't return a number, it should throw an error. (This is a condition I'm trying to catch in my code, YMMV)
To fix this I have done the following:
$string = "one";
$float = is_numeric($string) ? (float)$string : null;
echo $float; : ( Prints nothing )
Then before further processing the conversion, I can check and return an error if there wasn't a valid parse of the string.
For the sake of completeness, although this question is ancient, it's worth mentioning the filter_var() set of functions, which should not only handle the formatting bits itself, but also validate or sanitise the output, thus being safer to use in the context of a form being filled in by users (or, eventually, a database that might have some corrupted/inconsistent fields):
$InvoicedUnits = (float) filter_var($InvoiceLineItem->InvoicedUnits,
FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
$pricePerUnit = (float) filter_var($InvoiceLineItem->PricePerUnit,
FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
printf("The total is: %.2f\n", $InvoicedUnits * $pricePerUnit); // both are now floats and the result is a float, formatted to two digits after the decimal sign.
This sanitises the output (which will still remain a string) and will accept the current locale's setting of the decimal separator (e.g. dot vs. comma); also, there are more options on the PHP manual for validation (which will automatically convert the result to a float if valid). The results will be slightly different for different scenarios — e.g. if you know in advance that the $InvoiceLineItem will only have valid digits and symbols for floating-point numbers, or if you need to 'clean up' the field first, getting rid of whitespace, stray characters (such as currency symbols!), and so forth.
Finally, if you wish to have nicely-formatted output — since the total is expressed in a currency — you should also take a look at the built-in NumberFormatter class, and do something like:
$InvoicedUnits = (float) filter_var($InvoiceLineItem->InvoicedUnits,
FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
$pricePerUnit = (float) filter_var($InvoiceLineItem->PricePerUnit,
FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
$fmt = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo 'Total is: ' . $fmt->formatCurrency($InvoicedUnits * $pricePerUnit, 'EUR') . PHP_EOL;
This will also handle thousand separators (spaces, dots, commas...) according to the configured locale, and other similar fancy things.
Also, if you wish, you can use '' (the empty string) for the default locale string (set either by the server or optionally by the browser) and $fmt->getSymbol(NumberFormatter::INTL_CURRENCY_SYMBOL) to get the default 3-letter currency code (which might not be what you want, since usually prices are given in a specific currency — these functions do not take currency exchange rates into account!).
If you need to handle values that cannot be converted separately, you can use this method:
try {
// use + 0 if you are accounting in cents
$doubleValue = trim($stringThatMightBeNumeric) + 0.0;
} catch (\Throwable $th) {
// bail here if you need to
}

Categories