Home > OS >  how to convert php string to float keeping the decimal values
how to convert php string to float keeping the decimal values

Time:01-07

I have a string with the price '23,99', how do I convert this to float with php?

$price = '23,99';
$price_float = floatval($price);
echo $price_float;

CodePudding user response:

As you already discovered, you can replace the , with a .. There is another way which might be useful too. Using the NumberFormatter class, you can format the number in different ways. Based on a locale as well as using different formatters such as currency, percent or scientific. See the docs for all options. In you case, using the locale for Portugal, you could use:

$price = '23,99';
$numberFormatter = new NumberFormatter("pt-PT", \NumberFormatter::DECIMAL);
echo $numberFormatter->parse($price); // Wil output the float 23.99

CodePudding user response:

Alright, since I didn't find any php solution, and assuming "," is the separator, I made this function to overcome it

 function floatdec($a){
   $b = explode(',',$a);
   return floatval($b[0])   floatval($b[1])/100;
 }

 $price = '23,99';
 echo floatdec($price).'<br>';
 echo gettype(floatdec($price));

A few hours later... I found out that adding 0 (i.e. 0) to a string makes it an integer or double, the double only needs to be with the decimal point.

function floatdec($a){
    return str_replace(",",".",$a)   0;
}
  •  Tags:  
  • Related