Skip to content

Instantly share code, notes, and snippets.

@IdahoEv
Created August 12, 2014 16:15
Show Gist options
  • Select an option

  • Save IdahoEv/adfc01706bd50ef34d9a to your computer and use it in GitHub Desktop.

Select an option

Save IdahoEv/adfc01706bd50ef34d9a to your computer and use it in GitHub Desktop.
Accurate decimal math in Ruby with BigDecimal
2.1.0 :009 > 0.3.class
=> Float
2.1.0 :010 > 0.3 - 0.1
=> 0.19999999999999998
2.1.0 :011 > require 'bigdecimal'
=> true
2.1.0 :012 > BigDecimal.new(0.3, 10) - BigDecimal.new(0.1, 10)
=> #<BigDecimal:1011802e8,'0.2E0',9(18)>
2.1.0 :013 > (BigDecimal.new(0.3, 10) - BigDecimal.new(0.1, 10)).to_s
=> "0.2E0"
2.1.0 :014 > (BigDecimal.new(0.3, 10) - BigDecimal.new(0.1, 10)).to_f
=> 0.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment