Rumah > Artikel > pembangunan bahagian belakang > Bagaimana Menghuraikan Nilai Monetari dengan Tepat daripada Rentetan dalam Pelbagai Tempatan?
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.
Atas ialah kandungan terperinci Bagaimana Menghuraikan Nilai Monetari dengan Tepat daripada Rentetan dalam Pelbagai Tempatan?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!