Float vs Decimal in ActiveRecord

  • 3 Answer(s)

       The Computer science  professor saying never to use floats for currency.  IEEE specification defines floats in binary format. it stores sign, fraction and exponent to represent a Float  scientific notation for binary something like +1.43*10^2. Because of that, it is impossible to store fractions and decimals in Float exactly.

    Decimal format: 

    irb:001:0> "%.47f" % (1.0/10)
    => "0.10000000000000000555111512312578270211815834045" # not "0.1"!

    Just run: 

    irb:002:0> (1.0/10).to_s
    => "0.1" # the interprer rounds the number for you

    Small fractions,  compounding interests, or even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

    require "benchmark" 
    require "bigdecimal"
    d = BigDecimal.new(3) 
    f = Float(3)
    time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
    time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }
    puts time_decimal 
    #=> 6.770960 seconds 
    puts time_float 
    #=> 0.988070 seconds


    Using float  care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits.

    Use decimal if you are dealing with numbers that need to be precise and sum up to correct number like compounding interests and money-related things.

    Answered on December 22, 2018.
    Add Comment

    Rails 3.2.18:

       Decimal turns into integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue .

    Answered on December 22, 2018.
    Add Comment

    Alternative solution:

       In Rails 4.1.0, MySql database It can not save large fraction number with float data type. And I change the data type to decimal and working for me.

    Answered on December 22, 2018.
    Add Comment

  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.