$ ruby -v
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]
$ irb
irb(main):001:0> 0.692 * 3
=> 2.0759999999999996
I just ran into these numbers by chance. Is this related to Why Are Floating Point Numbers Inaccurate?.
$ ruby -v
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]
$ irb
irb(main):001:0> 0.692 * 3
=> 2.0759999999999996
I just ran into these numbers by chance. Is this related to Why Are Floating Point Numbers Inaccurate?.
Because floats are inaccurate, for arbitrary precision arithmetic in Ruby you can use BigDecimal
:
require 'bigdecimal'
require 'bigdecimal/util'
("0.692".to_d * 3).to_s('F')
=> "2.076"
Because BigDecimal
from the standard library will work for this, but we can solve this problem by using round
function -
(0.692 * 3).round(2) = 2.08