Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - mathematics operations

Tags:

math

ruby

I tried a few minutes ago simple math operation

<%=((3+2+1)/100).round(8)%>

The result is 0.06, but the result of the ruby code above is 0.0. I would expect the result should be 0.060000.

Why not? Thanks

like image 444
user1946705 Avatar asked Apr 27 '26 10:04

user1946705


2 Answers

(3+2+1)/100 

is 0 because the division is integer. Try

(3+2+1)/100.0

You see, if both arguments of / are integer, the result of the division is an integer (the whole part). If at least one of the arguments is floating-point, then the result is also floating-point.

like image 56
Armen Tsirunyan Avatar answered Apr 29 '26 05:04

Armen Tsirunyan


The dreadful integer arithmetic attacks again!

When you calculate ((3+2+1)/100), since all the operands are integers, Ruby uses integer arithmetic rather than floating point arithmetic.

If you do 7/100 it will also return 0, as it's rounded down to the nearest integer, which is 0.

like image 30
Augusto Avatar answered Apr 29 '26 04:04

Augusto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!