0

I have a some numbers stored in the database.

>> t = Total.first
=> #<Total id: 1, profit: 1058, number: 17, fees: 204, created_at: "2012-01-12 06:44:30", updated_at: "2012-01-12 06:51:13">

I want to perform division on one of the integers (an integer that will be updated frequently) and have the division on the newly updated integer. I basically just want to know what percent the profit is of 26,000

>> t.profit
=> 1058
>> t.profit / 26000
=> 0
>> t.profit.to_i / 26000
=> 0

I was hoping it would be as easy as something like this

def index  
  @t = Total.first
  @x = @t.profit / 26000
end

View

<%= @x %>

but it's not working, as the console suggested it wouldn't. Any hints?

2 Answers 2

4

An alternative to Sergio's method is to use Rails' built-in number_to_percentage view helper.

In your controller:

def index  
  @t = Total.first
  @x = @t.profit / 260.0  # = 26000 / 100
end

In your view:

<%= number_to_percentage @x, :precision => 0 %>

Or, if you're not using @t for anything else let the database do the math:

def index
  @t = Total.select('profit / 260 AS profit').first
end

Then...

<%= number_to_percentage @t.profit, :precision => 0 %>
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks a lot. I looked at number_to_percentage, trying this number_to_percentage(x) but it didn't work. I'll give yours a shot.
Your original solution is giving me 0% in the view when it should say 4%
@x = 0.038461538461538464. this code gave me .04 <%= number_to_percentage @x, :precision => 2 %>
Oh, I misread the docs. number_to_percentage expects, well, a percent value, e.g. 50 => 50%, not .5 => 50%. I've updated my answer.
I was sort of thinking the same thing, but I didn't do it right. I put this in the controller @x = @t.profit / 26000.0 and then on the next line @x = @x x 10.0 but it didn't allow me to multiply
|
2

It's an integer division, so the result is rounded. Convert one of your operands to float.

t.profit / 26000.to_f

To round that to two decimal places use something like this:

"%.2f" % (t.profit / 26000.to_f)

4 Comments

Thanks a lot. Can you make it a human readable number. i.e instead of 0.040692307692307694 I want 4%
O, you wrote your answer to my first comment that i deleted. sorry about that.
@Michael: There's the code for "0.04". How to turn it to "4%" - that's gonna be your homework :-)
someone did my homework for me...but to be honest, I did try to get the same solution as him (number_to_percentage) just didn't implement it right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.