user2158382
user2158382

Reputation: 4510

Floats, Decimals, or Integers

I have a rails app that process some data, and some of these data include numbers with decimals such as 1.9943, and division between these numbers and other integers. I wanted to know what the best way to store this was.

I thought of storing the numbers that would retain integers as integers and numbers that could become decimals as decimals. Although it was in a weird format like

#<BigDecimal:7fda470aa9f0,'0.197757E1',18(18)> 

it seems to perform the correct arithmetic when I divide two decimal numbers or a decimal with an integer. When I try to divide integers with integers, it doesn't work correctly. I thought rails would automatically convert the result into a proper decimal, but it seems to keep it as integer and strip the remainders. Is there anything I can do about this?

And what would be the best way to store this type of information? Should I store it all as decimals, or maybe floats?

Upvotes: 4

Views: 5197

Answers (2)

Floats suck
Floats suck

Reputation: 1

you don't need big precision to have problems with floats You should better avoid as much as possible floats. Ex: 123.6 - 123 => in floats it will give you 0,59.. in BigDecimal you will have 0.6

Upvotes: -1

dbyrne
dbyrne

Reputation: 61081

If you want to divide two integers without losing precision, you need to cast one of them to a Float or BigDecimal first:

irb(main):007:0> 2/3
=> 0
irb(main):008:0> Float(2)/3
=> 0.666666666666667

I am a bit confused when you say that you get different results when you divide a Float/Integer vs. Integer/Float? These should have the same result:

irb(main):010:0> Integer(2)/Float(3)
=> 0.666666666666667
irb(main):011:0> Float(2)/Integer(3)
=> 0.666666666666667
irb(main):012:0> String( BigDecimal('2')/3 )
=> "0.666666666666666666666666666666666666666666666666666667E0"
irb(main):013:0> String( 2/BigDecimal('3') )
=> "0.666666666666666666666666666666666666666666666666666667E0"

Can you provide a code example?

As far as storage goes, any integer data should be stored as an Integer regardless of its expected use in future calculations.

Storing Floats vs. BigDecimals depends on how much precision you require. If you don't require much precision, a Float will provide a double-precision representation. If you require a high degree of precision, BigDecimal will provide an arbitrary-precision representation.

Related: Ruby Numbers - Explains the difference between Integers, Floats, BigDecimals, and Rationals

Upvotes: 4

Related Questions