alex
alex

Reputation: 4914

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?

Upvotes: 0

Views: 51

Answers (2)

n-dru
n-dru

Reputation: 9430

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

Upvotes: 0

Sourabh Kumar Sharma
Sourabh Kumar Sharma

Reputation: 2807

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

Upvotes: 2

Related Questions