Search code examples
phpsymfonyintl

Change decimalseparator for a specific Language


In Russian language there is no fixed definition for the decimal separator character (GOST 8.417-2002 and GOST 2.004-88 - Russian state standards). The , (comma) is recommended but . (point) is possible.

The intl Extension in php defines the , (comma) as the decimal separator for Russian language.

I want to change the decimal separator character depend on users preference.

In my project I have an listener onKernelRequest where I set the locale. I assume this is the place where to change the predefined DECIMAL_SEPARATOR_SYMBOL.

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        // try to see if the locale has been set as a _locale routing parameter
        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            // if no explicit locale has been set on this request, use one from the session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        } 
        if ($locale == 'ru_RU') {
            // set NumberFormatter::DECIMAL_SEPARATOR_SYMBOL = '.' 
        }
}

Solution

  • we can use setlocale (http://php.net/manual/en/function.setlocale.php) to set the locale globally.

    But I dont think we can change the decimal separator globally. Php fetches the locale information from the operating system. I did not find any option that allows the locale information to be updated.

    One option is that you use a different locale for currency and a different locale for date/time, language etc. For example if your user selects Russian as their language, you can call setlocale(LC_NUMERIC, 'en_US'). This will force Php to use the American locale for formatting numbers