0

Should be Simple. I'm using Rails and doing something along the lines of:

<% n = 15 / 2 %>
<%= n %>

However, whenever I output variable n, it doesn't give me a decimal. Based on other calculations it looks like it's constantly rounding to floor, But I haven't added any sort of round method anywhere.

Could you explain why? I want it to actually round to ceil.

Andrew Ice
  • 831
  • 4
  • 16

3 Answers3

1

You can use Numeric#ceil

n = 15 / 2.0
n = n.ceil

Now, you need to either use .to_f or specify the numerator or denominator as a float ( 2.0 or 15.0) in order for it to be considered a floating point expression (as against an integer expression)

karthikr
  • 97,368
  • 26
  • 197
  • 188
  • I've got to wait a few minutes to give you an accepted answer, but thanks! It worked. I didn't know I actually had to provide a Decimal mark for it to detect it as a decimal. – Andrew Ice Oct 24 '13 at 01:35
1

You asked for explanation as well - the explanation is that because there are no decimal points, ruby is treating your numbers as integers. When integer division is done in ruby, anything after the decimal point is truncated. In order to not lose that info, you need to tell ruby to do floating point arithmetic, which you can do in either of the ways Karthikr explained.

TravisG
  • 11
  • 1
1

The issue is that 15 and 2 are not Floats but are Integers. You are doing Integer math.

You can coerce either to a float by using .to_f or adding that .0 and you will not have the same issue. If you want it to round up, then you can of course use .ceil

So, it isn't 'rounding to floor' it is a different concept.

vgoff
  • 10,980
  • 3
  • 38
  • 56