0
$ 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?.

Community
  • 1
  • 1
Pat Wangrungarun
  • 516
  • 4
  • 12

2 Answers2

1

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"
Casper
  • 33,403
  • 4
  • 84
  • 79
0

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
Amit Suroliya
  • 1,515
  • 1
  • 11
  • 21