首頁  >  文章  >  後端開發  >  如何在 PHP 中精確解析貨幣值:一種本地化感知方法?

如何在 PHP 中精確解析貨幣值:一種本地化感知方法?

Susan Sarandon
Susan Sarandon原創
2024-11-13 17:11:02258瀏覽

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