Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails decimal column

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.

like image 827
Dale Avatar asked Jun 23 '10 20:06

Dale


People also ask

How do you get decimals in Ruby?

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.

What is precision and scale in decimal in rails?

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.

What is precision and scale in rails?

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.


1 Answers

Since you're

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

use BigDecimal. Works fine

like image 161
Larry K Avatar answered Nov 03 '22 10:11

Larry K