-3

Hi I have the following question:

When I put (1+7/100) in ruby it gives 1.

This is very strange because normally this is how I calculate a 7% increase in Excel.

But when I put (1+7.0/100) it gives me 1.07 which is the correct answer I expected.

Why is ruby doing this? And how do you solve this issue in your calculations in ruby?

Runy
  • 57
  • 1
  • 7

1 Answers1

2

This has nothing to do with rounding.

Ruby does division differently on float than it does on an integer.

If you divide integers, you will always get an integer result.

If you divide with floats (or a mixture of integer and float), you will always get a float result.


Remember your order of operations, too. Ruby is going to handle the division before it handles the addition.

7/100 = 0 so 1+0 = 1

7.0/100 = 0.07 so 1+0.07 = 1.07

maček
  • 76,434
  • 37
  • 167
  • 198