Search code examples
ruby-on-railsrubydecimalprecisionbigdecimal

RoR decimal field with :precision => 10, :scale => 6 is not storing decimals


I have a decimal field that does not stores decimals, although the schema file says:

t.decimal  "kg", :precision => 10, :scale => 6

If I do:

(15,000 * 1,010)/1,000,000 

which should be 15.15

it will only show 15.00

On DDBB:

BigDecimal:7fd4cc707300,'0.15E2',9(36)

Solution

  • The result you're getting which I believe is 15 and not 15.15 is the way Fixnum division works. If you want decimals in your result, you need to include decimals in your operands:

    Example:

    # Decimal on denominator
    > (15000 * 1010)/1000000.0
    => 15.15
    
    # or, on numerator
    > (15000.0 * 1010)/1000000
    => 15.15
    

    You could then use this value to store in your kg field.