Don't Use Floats for Prices

September 10, 2015

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:

"1.03".to_f - ".42".to_f

#=> 0.61000000000000000001 

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.

Comments

comments powered by Disqus