Apply number_format to variable

0

I have 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 into 0.25. However, if I apply it this way:

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

My result is 0.00, how do I solve it?

    
asked by anonymous 12.12.2018 / 23:22

1 answer

1

Initially, the problem is that you are converting the string "0,25" into 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 the comma by point:

$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"
    
12.12.2018 / 23:37