Unformatting Monetary Values Accurately in Various Locales
Handling monetary values often requires the conversion of strings representing monetary amounts into numerical quantities. In PHP, the parsefloat() function can be utilized to achieve this. However, when dealing with values that may vary depending on locale, the decimal separator can differ. This poses a challenge for the straightforward parsefloat(str_replace(',', '.', $var)) approach.
A Comprehensive Solution
To address this locale-dependent issue, consider the following solution, which effectively extracts the float value while accounting for different decimal separators and thousand separators:
public function getAmount($money) { $cleanString = preg_replace('/([^0-9\.,])/i', '', $money); // Remove non-numeric characters $onlyNumbersString = preg_replace('/([^0-9])/i', '', $money); // Extract only numbers $separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1; // Determine extra separators $stringWithCommaOrDot = preg_replace('/([,\.])/i', '', $cleanString, $separatorsCountToBeErased); // Replace separators $removedThousandSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/i', '', $stringWithCommaOrDot); // Remove excess thousand separators return (float) str_replace(',', '.', $removedThousandSeparator); // Convert to float with dot as decimal separator }
Advantages and Caveats
This solution provides a reliable way to extract float values from monetary strings in various locales. Extensive testing has validated its accuracy for a wide range of scenarios, including values with commas or dots as decimal separators and thousands separators.
However, the caveat lies in its potential failure when dealing with decimal parts exceeding two digits. To address this limitation, modify the regular expression pattern in the code accordingly.
Practical Implementation
The solution is deployed within the library at https://github.com/mcuadros/currency-detector, which specializes in identifying and processing monetary values based on locale-specific settings.
위 내용은 다양한 로케일의 문자열에서 금전적 가치를 정확하게 구문 분석하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!