views:

33

answers:

2

If you specify your ActiveRecord column type to be decimal, Rails will return that database value as a ruby BigDecimal object.

My question is, when working with these fields and performing additional math on them, should I always use BigDecimal values in my calculations or are floating point values ok to use. I didn't know if it is a good practice to be mixing BigDecimal values and Floating Point values in the same calculations.

Mixed Example: BigDecimal.new('12.43') / 4.2

Same type Example: BigDecimal.new('12.43') / BigDecimal.new('4.2')

The reason I ask is because I'm a little gun shy of using floats because I need decimal accuracy. 0.1 + 0.7 will not equal 0.8 using floats.

A: 

stumbled across this article, it makes some good points for using BigDecimal

http://ramblingsof.justinwinkler.com/when-crap-just-doesnt-add-up

Geoff Lanotte
I like the require 'bigdecimal/util' helper
Dale
A: 

Since you're

... a little gun shy of using floats...

use BigDecimal. Works fine

Larry K
Yes, I think I should be using BigDecimal. My question is should I use BigDecimal for all numbers in the calculations. I did some testing and if you do this BigDecimal.new('1.2') + 1.1 the return value will be a float not a BigDecimal. So is it best practice to use all BigDecimal numbers when dealing with ActiveRecords Decimal column since it is using BigDecimal internally so you don't risk your calculation running into a weird float rounding problem?
Dale
Re: BigDecimal.new('1.2') + 1.1 returns float. You're right. Since that's the case, be sure to only operate with BigDecimal objects. Only convert when you want to output it.
Larry K
Also, remember to use BigDecimal.new('0.0') rather than 0.
Larry K