Home >Backend Development >PHP Tutorial >How to Convert Numbers with Comma Decimal Points (e.g., \'1.512.523,55\') to Floats in PHP?
Problem:
You have a list of numerical values where commas are used as decimal points and dots as thousand separators. You need to convert these values to floating-point numbers for mathematical operations.
Solution:
While you could consider using number_format, it does not support the specific format you've described. Using str_replace is indeed appropriate for this task, despite the potential for repeated replacements.
To convert the values to float:
$string_number = '1.512.523,55'; // Replace dots with empty string (removing thousand separator). $number_with_decimal_comma = str_replace('.', '', $string_number); // Replace comma with dot (converting decimal point). $number = floatval(str_replace(',', '.', $number_with_decimal_comma)); echo $number;
This method eliminates the need for multiple str_replace calls by performing both replacements in a single chain. It also ensures efficient conversion to a float value.
The above is the detailed content of How to Convert Numbers with Comma Decimal Points (e.g., \'1.512.523,55\') to Floats in PHP?. For more information, please follow other related articles on the PHP Chinese website!