2

How can I isolate cents and place them inside their own element? The output I'm looking for is this:

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

Notice there is no delimiter to separe the decimal units, and they're contained in their own sup tag. I know how to get <sup>$</sup>20.99 when using format: '<sup>%u</sup>%n', but this does not give me a way to isolate cents.

Any ideas?

4

2 回答 2

2

You are going to have to do it with substitution regex or something similar.

20.99.number_to_currency.sub(/\^([^\d]+)(\d+)([^\d]+)(\d+)/,     
'\1<sup>\2</sup>\3<sup>\4</sup>')
于 2013-04-29T03:53:35.027 回答
2

I personally use this method, it allow me to support I18n properly but also to only use the <sub> container when I want the number displayed in HTML.

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

if you like your currency unit to be in <sup> as well when using HTML, you could use this instead:

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

If you find any issue, please let me know.

于 2013-05-10T09:30:01.227 回答