Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Bagaimana Menghuraikan Nilai Monetari dengan Tepat daripada Rentetan dalam Pelbagai Tempatan?

Bagaimana Menghuraikan Nilai Monetari dengan Tepat daripada Rentetan dalam Pelbagai Tempatan?

DDD
DDDasal
2024-11-14 15:01:02646semak imbas

How to Accurately Parse Monetary Values from Strings in Various Locales?

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!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn