【问题标题】:How do I prevent ActiveSupport using units, tens, and hundreds localisations in number_to_human?如何防止 ActiveSupport 在 number_to_human 中使用单位、数十和数百本地化?
【发布时间】:2020-04-25 11:54:56
【问题描述】:

我已经设置了一个自定义语言环境,让 ActiveSupport 在调用 number_to_human 时使用短后缀。它给了我number_to_human(123456) => '123.4k',而不是number_to_human(123456) => '123.4 Thousand'

这一切都很好。 不起作用的是,虽然默认语言环境会留下较小的数字(即number_to_human(56) => 56),但我的自定义语言环境却不行。我将单位、十位和百位的后缀留空,但这会导致 number_to_human(52) => '5.2'(即 5.2 个十位)或 number_to_human(123) => '1.23'(代表 1.23 个百位)。

我如何告诉 ActiveSupport 根本不要使用单位、数十或数百 - 只留下 1000 以下的数字?

这是语言环境文件,如果有帮助的话 (config/locales/en-ABBREV.yml):

en-ABBREV:
  datetime:
    distance_in_words:
      x_seconds: '%{count}s'
      x_minutes: '%{count}m'
      about_x_hours: '%{count}h'
      x_hours: '%{count}h'
      x_days: '%{count}d'
      x_weeks: '%{count}w'
      about_x_months: '%{count}mo'
      x_months: '%{count}mo'
      x_years: '%{count}y'
  number:
    human:
      unit: ''
      ten: ''
      hundred: ''
      thousand: 'k'
      million: 'm'
      billion: 'b'
      trillion: 't'
      quadrillion: 'qd'

我在视图中对number_to_human 的调用如下所示:

number_to_human @posts.count, precision: 1, significant: false, locale: 'en-ABBREV',
                units: 'number.human', format: '%n%u'

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 activesupport


    【解决方案1】:

    查看该方法的文档,我认为您可以定义要使用的单位,如下所示。当units 中不包含某个键(如tens)时,则不会使用该单位。

    number_to_human(
      @posts.count, 
      format: '%n%u',
      precision: 1, 
      significant: false
      units: {
        thousand:    'k',
        million:     'm',
        billion:     'b',
        trillion:    't',
        quadrillion: 'qd'
      }
    )
    

    【讨论】:

      猜你喜欢
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2017-05-18
      • 2021-07-14
      • 1970-01-01
      相关资源
      最近更新 更多