How to Convert String to Float in PHP?

I’m trying to convert a string containing currency values, like BD 23.502 into a float number in PHP. This conversion is necessary for mathematical operations like addition or subtraction on the currency. So, I want to convert the string from BD 23.502 to 23.502. How can I achieve this in PHP?

There are multiple ways to convert a string containing currency values to a float in PHP.
If you only want to remove the BD from BD 23.502 you can use the str_replace() function.

// Your currency string
$amount = 'BD 23.502';

// Remove the 'BD' prefix and convert to float
$floatValue = (float) str_replace('BD ', '', $amount);

echo $floatValue; // Output: 23.502

But if the ‘BD’ prefix is not a fixed value, for example, if ‘BD’ can be ‘USD’ or a symbol like ‘$’ then the above solution will not work. You need to remove anything that is not number and (.) from the string.

So I think the below solution is best to use.

// Your currency string
$amount = 'BD 23.502';

// Remove anything that is not a number and dot and convert it to float
$floatValue = (float) preg_replace("/[^-0-9\.]/","", $amount);

echo $floatValue; // Output: 23.502