使用Rails number_to_currency </sup>在<sup>标签中包围美分

时间:2013-04-29 03:32:22

标签: ruby-on-rails ruby

我如何隔离美分并将它们放在自己的元素中?我正在寻找的输出是:

<sup>$</sup>20<sup>99</sup>

请注意,没有用于分隔十进制单位的分隔符,它们包含在自己的sup标记中。我知道在使用<sup>$</sup>20.99时如何获得format: '<sup>%u</sup>%n',但这并没有让我找到孤立美分的方法。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您将不得不使用替换正则表达式或类似的东西。

20.99.number_to_currency.sub(/\^([^\d]+)(\d+)([^\d]+)(\d+)/,     
'\1<sup>\2</sup>\3<sup>\4</sup>')

答案 1 :(得分:1)

我个人使用这种方法,它允许我正确地支持I18n,但是当我想要用HTML显示的数字时,也只使用<sub>容器。

def formated_price(price, currency, options = {})
  html = options[:html].nil? ? false : options[:html]

  money = number_to_currency(price, unit: currency) || h('')
  if html
    separator = I18n.t('number.currency.format.separator')
    tmp = money.split(separator)
    tmp[1] = tmp[1].sub(/\A(\d+)(.*)\z/, content_tag(:sup, separator + '\1') + '\2') if tmp[1]
    money = tmp.join.html_safe
  end
  money
end

如果您希望您的货币单位在使用HTML时也在<sup>,则可以使用此代码:

def formated_price(price, currency, options = {})
  html = options[:html].nil? ? false : options[:html]
  if html
    money = number_to_currency(price, unit: content_tag(:sup, currency)) || h('')
    separator = I18n.t('number.currency.format.separator')
    tmp = money.split(separator)
    tmp[1] = tmp[1].sub(/\A(\d+)(.*)\z/, content_tag(:sup, separator + '\1') + '\2') if tmp[1]
    money = tmp.join.html_safe
  else
    number_to_currency(price, unit: currency) || h('')
  end
end

如果您发现任何问题,请告诉我。