Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefix number with "+" if it is positive - Ruby / Rails 4

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?

like image 287
karns Avatar asked Jan 17 '15 19:01

karns


1 Answers

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.

like image 96
Shamsul Haque Avatar answered Sep 28 '22 00:09

Shamsul Haque