0

I was wondering if there was a way to round a number in the model, so that I would not have to round the number to my specified decimal places anywhere else but there.

I looked at these two posts, but neither answered my question:

The first being a supposed duplicate of the second, but in my opinion it is not. Regardless, neither answered my question clearly.

Is there any possible way of rounding floats once in the model?

Community
  • 1
  • 1
Santi Gallego
  • 202
  • 1
  • 18
  • Try a `:before_validation` hook -- It has been years since I've used Rails but that's what I'd have done if I was in your shoes. Of course the database will still store a float but it will be the rounded value +/- the machine epsilon. – zetavolt Jul 22 '16 at 19:16

2 Answers2

1

Just using currencies as an example!

  • Use a hook (:before_save)
  • Write down as many attributes you need inside :round_decimals.
# models/Currency.rb
class Currency < ApplicationRecord
  before_save :round_decimals

  private

  def round_decimals
    self.spot_rate = self.spot_rate.round(2)
  end
end
Richard Jarram
  • 899
  • 11
  • 22
0

I think what a good way would be is to overwrite the setter. (in your case, but in general I would use an integer if you have to store rounded floats.)

class Xyz < ActiveRecord::Base
  def my_float=(value)
    if value.is_a? Float
      super(value.round)
    else
      super
    end
  end
end
siegy22
  • 4,295
  • 3
  • 25
  • 43