-2

I have the following object -

Reckoner Load (0.2ms)  SELECT  "reckoners".* FROM "reckoners" WHERE
  "reckoners"."id" = ? LIMIT 1  [["id", 2]]
=> #<Reckoner id: 2, group: "test FTEProrated", description: "try new calc", 
     leave: 28, abscence: #<BigDecimal:7fab221cf438,'0.1E2',9(27)>,
     created_at: "2014-10-06 15:56:10", updated_at: "2014-10-06 16:14:32",
     FTEProRated: #<BigDecimal:7fab221ca1e0,'0.0',9(27)>>

If I've done my calculation correctly, FTEProRated should be about 0.8 - but it's being displayed as 0.0. Where am I going wrong?

The calculation is carried out in the controller before the object is saved -

in update -

pro_rate_this @reckoner

...

def pro_rate_this(reckoner)
  reckoner.FTEProRated = (260-reckoner.leave)/260
end

when I change the calc to test what's being saved, it all seems okay - for example, this -

def pro_rate_this(reckoner)
  reckoner.FTEProRated = (260-reckoner.leave)
end

gives a value of 232 when reckoner.leave == 28. It's only when the value becomes < 1 that it seems to be a problem, though that could be coincidence.

dan
  • 1,030
  • 1
  • 9
  • 24
  • how are you displaying it? – Mandeep Oct 06 '14 at 16:53
  • just as `<%= @reckoner.FTEProRated %>` in a view – dan Oct 06 '14 at 16:58
  • Is `FTEProRated` a column from your database? If so, what is the column type? If not, please show us the code that calculates/assigns it. – Jordan Running Oct 06 '14 at 17:09
  • Where is the calculation? – infused Oct 06 '14 at 17:09
  • thanks all - have updated the question as suggested. Hi @lurker - yep I saw that too, but the result of the calc on paper is 0.8 – dan Oct 06 '14 at 17:20
  • possible duplicate of [Why is division in Ruby returning an integer instead of decimal value?](http://stackoverflow.com/questions/5502761/why-is-division-in-ruby-returning-an-integer-instead-of-decimal-value) – Brad Werth Oct 06 '14 at 17:20
  • Hi Brad - have just had a look, and it sort of is - casting the calculation .to_f fixes the problem, but that's not the accepted answer on the question you linked to. What's the form in this circumstance? Should I answer the q myself? – dan Oct 06 '14 at 17:27
  • It's the most highly upvoted answer, FWIW. It's basically the same solution, just a different approach, anyway. – Brad Werth Oct 06 '14 at 17:37

1 Answers1

-1

Math... make sure you're dividing by floats if you want your answer to be a float.

def pro_rate_this(reckoner)
  reckoner.FTEProRated = (260-reckoner.leave)/260.0
end

See the denominator there? Just add that .0 to the 260 and report back.

Dudo
  • 4,002
  • 8
  • 32
  • 57