0

I've got this method:

def progress_percentage
  (progress_index / positive_statuses.size) * 100
end

It's returning 0 and it should be 38.46.

@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

t56k
  • 6,769
  • 9
  • 52
  • 115

2 Answers2

5

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.

moveson
  • 5,103
  • 1
  • 15
  • 32
0

You can use Fixnum#fdiv and Float#round here:

def progress_percentage
  ((progress_index.fdiv positive_statuses.size) * 100).round 2
end

as requested, returns your number rounded to two decimal places.

Example

((5.fdiv 13)*100).round 2
#=> 38.46 
Community
  • 1
  • 1
Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35