When parsing financial data in PHP, it's often necessary to convert strings representing monetary values into floating-point numbers. To achieve this, a common approach involves replacing commas with periods in the string and then using the floatval() function. However, this method relies on a fixed decimal separator (period) and may not be suitable for locales where a comma is used as the separator.
A more robust solution that handles both decimal separators is presented in the following code:
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); }
This solution consists of several steps:
This approach ensures that unformatted monetary values are parsed correctly, regardless of the locale-specific decimal separator. However, it's important to note that it assumes the decimal part of the monetary value has no more than two digits.
Example Tests:
['1,10 USD', 1.10], ['1 000 000.00', 1000000.0], [' 000 000.21', 1000000.21], ['£1.10', 1.10], ['3 456 789', 123456789.0], ['3,456,789.12', 123456789.12], ['3 456 789,12', 123456789.12], ['1.10', 1.1], [',,,,.10', .1], ['1.000', 1000.0], ['1,000', 1000.0]
The above is the detailed content of How to Refine Unformatted Money Values in PHP?. For more information, please follow other related articles on the PHP Chinese website!