【问题标题】:Change decimalseparator for a specific Language更改特定语言的小数分隔符
【发布时间】:2017-09-20 19:27:33
【问题描述】:

在俄语中,小数分隔符没有固定定义(GOST 8.417-2002 和 GOST 2.004-88 - 俄罗斯国家标准)。推荐使用,(逗号),但也可以使用.(点)。

intl php 中的扩展将,(逗号)定义为俄语的小数分隔符。

我想根据用户的喜好更改小数分隔符。

在我的项目中,我有一个侦听器onKernelRequest,我在其中设置了语言环境。我认为这是更改预定义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 = '.' 
        }
}

【问题讨论】:

  • 你不能只用number_format()吗?
  • 这个答案可能会提供您正在寻找的内容:stackoverflow.com/a/38575177/457268
  • @DevDonkey:原则上是的,但是我必须触摸每个使用函数 number_format() 的地方。并且必须决定是否必须更改标准值(language == 'ru_RU')(language != 'ru'RU')。
  • @K0pernicus:你提到的答案不适合我的问题。那里有一个全局树枝设置。我想根据所选语言(和用户偏好)进行此设置。

标签: php symfony intl


【解决方案1】:

我们可以使用 setlocale (http://php.net/manual/en/function.setlocale.php) 来全局设置语言环境。

但我认为我们不能全局更改小数点分隔符。 Php 从操作系统中获取语言环境信息。我没有找到任何允许更新语言环境信息的选项。

一种选择是您为货币使用不同的区域设置,并为日期/时间、语言等使用不同的区域设置。例如,如果您的用户选择俄语作为他们的语言,您可以调用 setlocale(LC_NUMERIC, 'en_US')。这将强制 PHP 使用美国语言环境来格式化数字

【讨论】:

  • 我找到了解决我的问题的方法。我创建了一个覆盖 localizedcurrency 过滤器功能的树枝扩展:public function localizedcurrency($number, $currency = null, $locale = null) { $formatter = twig_get_number_formatter($locale, 'currency'); if ($formatter->getLocale() == 'ru') { $formatter->setSymbol(\NumberFormatter::MONETARY_SEPARATOR_SYMBOL, '.'); } return $formatter->formatCurrency($number, $currency); }
猜你喜欢
  • 2013-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多