Apply number_format in variable

Asked

Viewed 27 times

0

I got the following:

$_POST['stock_unity_push'] = "R$ 0,25";
$stock_unity_push = str_replace(".", "", str_replace("R$ ", "", $_POST['stock_unity_push']));

I need to turn this result to 0.25. However, if I apply it that way:

$stock_unity_push = number_format((float)$stock_unity_push, 2, '.', ',');

My score is 0.00, how to solve?

1 answer

1


Initially, the problem is that you are converting the string "0,25" in float:

$foo = "R$ 0,25";
$stock_unity_push = str_replace(".", "", str_replace("R$ ", "", $foo));
var_dump($stock_unity_push); // string(4) "0,25"
echo '<br/>';
$foo = (float) $stock_unity_push;
var_dump($foo); // float (0)
$stock_unity_push = number_format($foo, 2, '.', ',');

Solution: Replace comma with dot:

$foo = "R$ 0,25";
$stock_unity_push = str_replace(".", "", str_replace("R$ ", "", $foo));
var_dump($stock_unity_push); // string(4) "0,25"
// Solução:
$stock_unity_push = str_replace(',', '.', $stock_unity_push); // "0,25" vira "0.25"
echo '<br/>';
$foo = (float) $stock_unity_push;
var_dump($foo); // float (0)
$stock_unity_push = number_format($foo, 2, '.', ',');
echo '<br/>';
var_dump($stock_unity_push); // string(4) "0.25"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.