CD-RUM CD-RUM - 10 months ago 95
Ruby Question

Rails: bad math?

I've got this method:

def progress_percentage
(progress_index / positive_statuses.size) * 100

It's returning
and it should be

@lead.progress_index # this is 5
@lead.positive_statuses.size # this is 13
@lead.progress_percentage # this is 0?

The first two values have been confirmed. What is going on? Edit: confirmed in the view here.

enter image description here

Answer Source

Welcome to integer math. In Ruby (like many languages) an integer divided by an integer returns an integer. In your case, 5 / 13 returns 0. If either your numerator or denominator is converted to a float before you run this operation, you will get a float in return, and the expected answer will result.

You can convert to a float using to_f. So (progress_index.to_f / positive_statuses.size) * 100 should work.