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.
Ruby has a built in function round() which allows us to both change floats to integers, and round floats to decimal places. round() with no argument will round to 0 decimals, which will return an integer type number. Using round(1) will round to one decimal, and round(2) will round to two decimals.
For clarity's sake: the precision is the number of significant digits, while the scale is the number of digits that can be stored following the decimal point. For example, the number 123.45 has a precision of 5 and a scale of 2. A decimal with a precision of 5 and a scale of 2 can range from -999.99 to 999.99.
Precision is the total number of digits in the number, both before and after the decimal point. Scale is the number of digits after the decimal.
Since you're
... a little gun shy of using floats...
use BigDecimal. Works fine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With