From: frosty Date: 2011-12-16T08:14:39+09:00 Subject: Re: round float to integer if whole number -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 12/15/2011 05:21 AM, Gunther Diemant wrote: >> That test does not work reliably: > You're right, but floating point numbers don't work reliably (as > one can see in your examples, one has always conversion and > rounding errors) > > Nonetheless if one has to work with floating point numbers it is > surly better to define equality in terms of some delta error > tolerance. > I would think the most accurate way to do it would be to convert the number to a string, split on the '.' and then check if a number besides '0' is in the second part of the list. For example irb(main):001:0> whole, nonwhole = 2.0 , 2.333 => [2.0, 2.333] irb(main):002:0> puts whole.class() Float => nil irb(main):003:0> puts nonwhole.class() Float => nil irb(main):004:0> whole_split = whole.to_s.split('.')[1] => "0" irb(main):005:0> nonwhole_split = nonwhole.to_s.split('.')[1] => "333" irb(main):006:0> /[1-9]/.match(whole_split) => nil irb(main):007:0> /[1-9]/.match(nonwhole_split) => # - -- frosty public key: unluckyfrosty.net/public_key -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (GNU/Linux) iQEcBAEBAgAGBQJO6n9WAAoJEMWQxuocG7AklLsH/AtnrXbWH29Hr+FrZwp0/LWt R41fQ9sAezWmYLdERdh/07jzv0ZEOlTjUg+yZ/HRBeA5xvxeIwMS0HNANvnUDeKt YcPFggAF0oG6z1/a9LAJpRJUlidnxFfQRrScRd/v5T6ojuSewFcKFjJW3Tkps85v 1NhZUQRuIJTO+UIoCmsp3ErHsDzs6wgSbSw6eJ0DjkCJdzqnSMLsUohqN0B1MuuR nhulfXfOmpGza9JbqAbMfNc9JaIaxn2HAMZA2Iag0R8yC4S/BTvNOtNasVHeFYxD AjteZtxkXZRjV0iKY5tKQHe1Jb1PqCuLTUPz97x+SBsmD3ILUwsfLU3SZ0x3+tI= =i6EY -----END PGP SIGNATURE-----