Search code examples
ruby-on-railsmodelcalculated-field

How to have two digits after comma in rails?


I am trying to make calculation in my model, but i'm not able to get two digits after the comma.

I tried different ways but when my result should be for example 7.50 or 7.25 I get 7 or 8.

if you can tell me where the issue is, that would be very kind of you. Thanks.

My schema.rb

  create_table "timesheets", force: true do |t|
    t.time     "working_start"
    t.time     "working_end"
    t.decimal  "billable_hours"
    t.integer  "weeknum"
    t.date     "date"
    t.decimal  "breaks"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

My model

class Timesheet < ActiveRecord::Base
## current week number

default_value_for :weeknum do
    Time.now.strftime('%V')
end

## relation

belongs_to :user

## Worked hours

before_create :calculate_worked_hours

private
    def calculate_worked_hours
      #breacalculk = (breaks.to_i * 60)
      #totalhours = (working_end.to_i - working_start.to_i) - (breaks.to_i * 60)
      
      self.billable_hours = ((working_end.to_i - working_start.to_i) - (breaks.to_i * 60)) / 3600
    end

end


Solution

  • Change / 3600 to / 3600.0

    When both numerator and denominator are integers, the result will be an integer; so 5/2 will give 2. If one of them is a float, then the result will be a float. Eg: 5.0/2 = 2.5