首页  >  文章  >  后端开发  >  如何在 PHP 中精确解析货币值:一种本地化感知方法?

如何在 PHP 中精确解析货币值:一种本地化感知方法?

Susan Sarandon
Susan Sarandon原创
2024-11-13 17:11:02257浏览

How to Parse Monetary Values with Precision in PHP: A Localization-Aware Approach?

Parsing Monetary Values with Precision in PHP

Parsing financial data with varying formats can be a challenge, especially when considering locale-specific separators. This issue arises when trying to convert a string representation of money, such as "75,25 €", into a floating-point value.

While the common approach involves using parsefloat() after replacing commas with dots, it falls short when dealing with locales that use commas as decimal separators. To address this limitation, a more comprehensive solution is required.

A Localization-Aware Solution

The proposed solution addresses the need for localization awareness by relying on regular expressions to extract the numeric value from the input string. It effectively handles both commas and dots as decimal separators, preserving the correct representation regardless of the locale.

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);
}

Testing the Solution

To validate its effectiveness, the solution was tested with various input formats, including:

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

The results demonstrate the solution's ability to extract floating-point values accurately, irrespective of the input format.

Limitations and Source

While the solution excels in handling various locales, it does have a limitation regarding decimals with more than two digits. The codebase is available at https://github.com/mcuadros/currency-detector, providing a practical implementation for parsing monetary values in diverse locales.

以上是如何在 PHP 中精确解析货币值:一种本地化感知方法?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn