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;
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
Alright, since I didnt found any php solution, and assuming "," is the separator, had 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... found out that the string + 0 makes it integer or double, the double only needs to be with the point.
function floatdec($a){
return str_replace(",",".",$a) + 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.