0

This should just work with ease:

b = Balance.first
b.total = 2.20
b.save #=> 2.2
b #=> 2

Total's table column is an integer :integer. Do I need to set the table as float as the decimal is not registered?

Here is the Rails 4 part; when the form is submitted, I have in the Balance model:

...

before_save :balance_to_float

def balance_to_float
  self.total = self.total.to_f
end

...

Sill not getting the float. Have I missed something with Ruby 2.3?

10
  • 1
    Set total column as a float and it should be fine Commented Mar 1, 2016 at 11:17
  • Tried that but still not showing as float. Its not in the db as float. Im using postgres Commented Mar 1, 2016 at 11:18
  • 1
    You will need to migrate old data since they have been cast as integers before you set the column as float Commented Mar 1, 2016 at 11:19
  • 1
    I see, that's the fractional part. BTW, you should not use float for currency values. Either use decimal (BigDecimal in Ruby and DECIMAL in SQL) or use an integer and store the cents (i.e. store 2.2 as 220). The latter is used by the money-rails gem. Commented Mar 1, 2016 at 14:15
  • 1
    @Sylar you don't have to use a gem. money-rails provides mapping between cent values stored as integers and instances of Money. You can easily write your own wrappers or just use decimal. Commented Mar 1, 2016 at 14:58

1 Answer 1

1

You cannot store a float in an integer column. Because an integer (from the Latin integer meaning "whole") is a number that can be written without a fractional component.

You must change your column's type to float or decimal (depending on your needs).

Sign up to request clarification or add additional context in comments.

1 Comment

Yes I had to revisit my ruby knowledge and saw that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.