ActiveRecord Type For Currency

Jelani Woods
1 min readAug 22, 2018

--

I’m building an app where an ActiveRecordhas a price field and got curious to see what type is recommended for currency. My first instinct was to use afloat since currency requires decimals and integer seemed out of the question. While looking up all ActiveRecord types, I realized there actually is a decimal type that seemed like it would also work as well as floats. So I delved deeper and found this stackoverflow answer that was very informative.

Basically, never use a floatfor currency since floats are base 2 numbers and money and decimals are base 10. Because of this, fractional numbers cannot be stored on your machine the same way, which leads to lower accuracy when using floats with small fractions.

Update: Its also important to know that you can use an integer to store price more easily with the acts_as_decimal (formally, act_as_dollars) plugin, that apparently will take in a value like, 12.34 , store it as 1234 , but still return 12.34 which seems pretty neat, but I noticed it after switching to decimal so I might try it on my next build!

--

--