开发者

rails format positive and negative numbers

开发者 https://www.devze.com 2023-04-12 19:55 出处:网络
I\'m trying to format a column of numbers in rails - using number_to_currency.I want to display negative numbers with ()s - which is easy to do using the negative_format option.However, when I do this

I'm trying to format a column of numbers in rails - using number_to_currency. I want to display negative numbers with ()s - which is easy to do using the negative_format option. However, when I do this, the decimal points in a column of numbers doesn't line up. I want to add a trailing space to the format for positive numbers - %u%n, only I do开发者_如何学Cn't know how to do that - can anyone give me the right way to format in a trailing space?

rails format positive and negative numbers


There are a couple of ways you can pad the positive numbers with a little bit of space, either:

  1. Use a fixed width font and a nonbreaking space  
  2. Apply a class to the enclosing element of your positive numbers (or wrap in a span) and then use internal padding to add space to the right.

The first approach mixes presentation with content, but has the advantage of working with any font size (or user resized fonts). With the second solution your HTML is cleaner and in well-behaved browsers things will work well, but your mileage will vary with less modern ones.

Here's a quick implementation of the first option:

def pad_positives(number_string)
  unless number_string[0,1] == '('
    number_string += '%nbsp;'
  end
  number_string
end

You could drop this in your appropriate helper file and then do something like this in your view:

<%= pad_positives(number_to_currency(number, ...)) %>

Note this function expects a string, so it will choke if you pass it a number. Hope this helps!


Let's say you have the variable amount in your loop:

<td class="amount">
  <%= (amount >= 0) ? "#{number_to_currency(amount)}&nbsp;" : "(#{number_to_currency(amount)})" %>
</td>

And in your CSS:

.amount {
  font-family:monospace;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消