Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

In ruby Why 10 / 3 return 3 not 3.33333333333333 ?

user-image
Question ajoutée par Adel Ezat Fawzy Ellozy , Webdeveloper. , Saudi Arabian Maritiem Sports Federation
Date de publication: 2017/03/09
Yusuf Daniju
par 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