I recently learned the hard way the importance of avoiding the use of Floats for storing currency values in Ruby. Floats abide by ‘floating point arithmetic’ and thus results in the representation of real numbers via a formulaic expressions, namely to serve as a tradeoff between range in precision. More info about the topic can be read here.
What this meant was that storing prices in Floats often led to an accumulation of small values that overtime resulted in inaccurate prices. For example:
A better option would be to use
Decimal when using prices. What I’ve commonly seen used has been
add_column :table, :price, :decimal, :precision => 8, :scale => 2.