Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

In ruby Why 10 / 3 return 3 not 3.33333333333333 ?

user-image
Question added by Adel Ezat Fawzy Ellozy , Webdeveloper. , Saudi Arabian Maritiem Sports Federation
Date Posted: 2017/03/09
Yusuf Daniju
by Yusuf Daniju , Software Engineering Consultant , Growphile Limited

When you write 10/3, it is assumed that you're making an integer division and so an integer is returned. Casting any of the numerator or denominator to decimal or float will make you get a result in decimal or float. eg

10.0/3 or 10.to_f/3

10/3.0 or 10/3.to_f

10.fdiv 3

10.0/3.0 or 10.to_f/3.to_f

 

All these will give you a fairly accurate result. However, it might not be 3.3333333333 as expected due to known issues with floating point numbers.

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.