Search code examples
phpmoney-format

PHP working with money from different locales


I can not use the money_format or NumberFormatter class. I gave the users the possibility to define which decimal separator they want to use - a comma or a dot.

// , or .
$decimal_separator = getUserDecimalSeparator();

Now, the user may introduce into the input field the following values:

1,200.10
1.500,21
1,50
1.35
1500.10
1900,21

What I need is to format those values to insert properly into the database. My field in database is a double(10,2).

In order to handle the values the user inserted I want them to be converted to (always with a dot as decimal separator and without separator of thousands):

1200.10
1500.21
1.50
1.35
1500.10
1900.21

So I have thought about a function which would help me converting the values.

function formatMoneyToDatabase($value, $separator)
{
    $value = str_replace('.', ',', $value); 

    if($separator == ',')
        return number_format($value, 2, '.', '');

    return number_format($value, 2, ',', '');
}

But this won't work for several reasons:

  1. The value might have two, three or more separators (1.000.000,50 or 1,000,000.50)
  2. I need to identify the separator of the value
  3. I need to verify if the value has any decimal values

Solution

  • Solved, I believe.

    I found a solution in stackoverflow which I can't link to because I lost the link, but the solution is by regex.

    if(!function_exists('formatMoneyToDatabase'))
    {
        function formatMoneyToDatabase($value)
        {
            return preg_replace('/[^\d]/', '', $value) / 100;
        }
    }
    
    100,000,000.12 -> 100000000.12
    75.000,12      -> 75000.12
    50.000.000     -> 50000000
    12,000,000     -> 12000000
    

    NOTE: I have validated the price before in another regex function.

    return preg_match('/^[0-9]+(?:\.[0-9]{2,' . $decimal_places . '}+)?$/', $price);