Home >Backend Development >PHP Tutorial >How to Convert Numbers with Comma Decimal Points (e.g., \'1.512.523,55\') to Floats in PHP?

How to Convert Numbers with Comma Decimal Points (e.g., \'1.512.523,55\') to Floats in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 08:55:13785browse

How to Convert Numbers with Comma Decimal Points (e.g.,

Converting a Number with Comma Decimal Point to Float

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:

  1. Use str_replace to replace the thousand separator dots with an empty string.
  2. Use str_replace again to replace the comma decimal point with a dot.
  3. Use floatval to convert the resulting string to a 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn