سؤال

Running ruby 1.8.7.

(1.005 * 100).round result: 100

(1.006 * 100).round result: 101

100.5.round result: 101

(1.005 * 100) result: 100.5

What is going on here? Can someone try this in the latest version of ruby please? Thanks!

هل كانت مفيدة؟

المحلول

Floating Point Math is what's going on.

For the last one, I do not get 100.5, and you aren't either, even if for some reason it's displaying as that:

Loading development environment (Rails 3.2.8)
1.9.3p194 :001 > (1.005 * 100).round
 => 100 
1.9.3p194 :002 > (1.006 * 100).round
 => 101 
1.9.3p194 :003 > 100.5.round
 => 101 
1.9.3p194 :004 > (1.005 * 100)
 => 100.49999999999999 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top