How to Refine Unformatted Money Values in PHP?

Mary-Kate Olsen
Release: 2024-11-23 22:28:16
Original
542 people have browsed it

How to Refine Unformatted Money Values in PHP?

Refining Unformatted Money Values in PHP

When parsing financial data in PHP, it's often necessary to convert strings representing monetary values into floating-point numbers. To achieve this, a common approach involves replacing commas with periods in the string and then using the floatval() function. However, this method relies on a fixed decimal separator (period) and may not be suitable for locales where a comma is used as the separator.

A more robust solution that handles both decimal separators is presented in the following code:

public function getAmount($money)
{
    $cleanString = preg_replace('/([^0-9\.,])/i', '', $money);
    $onlyNumbersString = preg_replace('/([^0-9])/i', '', $money);

    $separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;

    $stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
    $removedThousandSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '',  $stringWithCommaOrDot);

    return (float) str_replace(',', '.', $removedThousandSeparator);
}
Copy after login

This solution consists of several steps:

  • Sanitization: The input string is first sanitized by removing any non-numeric characters.
  • Count Separators: It then counts the number of decimal separators (commas or periods) present in the sanitized string.
  • Parse: Using regular expressions, the separators are removed, leaving only the numeric portion of the string.
  • Conversion: Finally, the cleaned string is converted to a floating-point number.

This approach ensures that unformatted monetary values are parsed correctly, regardless of the locale-specific decimal separator. However, it's important to note that it assumes the decimal part of the monetary value has no more than two digits.

Example Tests:

['1,10 USD', 1.10],
['1 000 000.00', 1000000.0],
[' 000 000.21', 1000000.21],
['£1.10', 1.10],
['3 456 789', 123456789.0],
['3,456,789.12', 123456789.12],
['3 456 789,12', 123456789.12],
['1.10', 1.1],
[',,,,.10', .1],
['1.000', 1000.0],
['1,000', 1000.0]
Copy after login

The above is the detailed content of How to Refine Unformatted Money Values in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template