PHP: string with decimals strips decimals when converting to float - php

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

Related

How to read a PHP variable as a numeric variable to make some calculation?

I am having problems with a variable which reads 17,50 for calculation. The variable is part of an array and i am just getting the value 17.00
$product_price_tmp = intval(str_replace(",",".",$custom_values['product_price'][0]));
and i tried the following
$product_sub_total = sprintf("%.2f",$product_price_tmp);//reads 17.00
$product_sub_total = $product_price_tmp;//reads 17
I didn't notice the problem as all my test price values were rounded numbers.
Any tips?
Replace this
$product_price_tmp = intval(str_replace(",",".",$custom_values['product_price'][0]));
with this
$product_price_tmp = floatval(str_replace(",",".",$custom_values['product_price'][0]));
You don't need intval since it is not int you intend to get. It is enough to cast float type here:
$product_price_tmp = (float) str_replace(",",".",$custom_values['product_price'][0]);
var_dump($product_price_tmp);
//float 17.5

Use php money format and remove the numbers after the decimal place for GBP

I want to format some numbers from my analytics into currency using the GB money format but as its for a dashboard and doesn't need to be that precise so I want to remove the pence (numbers after the decimal place) and round it which helps with the css layout, how do I do this? Rounding up or down to the nearest pound would be fine.
My code is as follows:
//set locale for currency
setlocale(LC_MONETARY, 'en_GB');
$sales = '8932.83';
echo utf8_encode(money_format('%n', $sales));
This outputs: £8,932.83
However how do I round this to be output as just £8,932 without anything after the decimal place.
I want to use currency format as sometimes the figure is negative in which case money_format returns the number like -£8,932.83 which is preferable to £-8,932 (pound and negative symbol around the wrong way) which is what happened when I formatted using number_format like so:
echo '£'.number_format($sales, 0, '', ',');
Do you want to round it or get rid of the decimals?
To round it which would be 8933 would be:
echo utf8_encode(money_format('%.0n', $sales));
To get rid of the decimals, you could use floor (which rounds down):
echo utf8_encode(money_format('%.0n', floor($sales)));
As the money_format() has been deprecated in PHP 7.4 and removed in PHP 8.0, the suggested function for formatting currency is now NumberFormatter::CURRENCY.
Solving this problem for example would be done this way:
$sales = 8932.83;
$sales = (int)$sales;
$numFormat = new NumberFormatter("en_GB", NumberFormatter::CURRENCY);
$sales = $numFormat->formatCurrency($sales, "EUR");
$sales = str_replace('.00', '', $sales);
echo $sales;

Convert string to integer and multiply two integers

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

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)

Categories