I'm simply trying to get a percentage.
irb(main):001:0> (25 / 50) * 100
=> 0
This should most definitely equal 50, as confirmed by my calculator (copied and pasted the same equation into gcalc). Why does Ruby refuse to do this?
The round() method can be used to round a number to a specified number of decimal places in Ruby. We can use it without a parameter ( round() ) or with a parameter ( round(n) ). n here means the number of decimal places to round it to.
It's doing integer division.
Basically, 25 is an integer (a whole number) and so is 50, so when you divide one by the other, it gives you another integer.
25 / 50 * 100 = 0.5 * 100 = 0 * 100 = 0
The better way to do it is to first multiply, then divide.
25 * 100 / 50 = 2500 / 50 = 50
You can also use floating point arithmetic explicitly by specifying a decimal point as in:
25.0 / 50.0 * 100 = 0.5 * 100 = 50
Because you're dividing an integer by an integer, so the result is getting truncated to integer (0.5 -> 0) before getting multiplied by 100.
But this works:
>> (25 / 50) * 100
=> 0
>> (25.0 / 50) * 100
=> 50.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With