I am wondering what the conventional Rails way AND Ruby way is to prepend a "+" sybmol to a number if it is positive.
Example:
<%= @number #5 %>
Should output:
+5
By default, negative will display properly:
<%= @number #-3 %>
Outputs:
-3
I know I could do something like the follwing:
<%= (@number > 0)? '+':'' %><%= @number %>
But I don't like that. What is a good way to do this in both Ruby & Rails, or for both if it is the same?
Look at the sprintf method
sprintf("%+d", 123)
1.9.3-p392 :005 > sprintf("%+d", 123)
=> "+123"
1.9.3-p392 :008 > sprintf("%+d", -123)
=> "-123"
And in the view:-
<%= sprintf("%+d", 123) %>
<%= sprintf("%+d", @number) %>
If @number
will be a positive number then a +
sign will appear or if it is a negative number the a -
sign will appear in the view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With