Represent repeating decimals in Rails model
What's a good way to represent repeating decimals in the database?
My current thought is to separate it into 2 pieces in the Rails model:
take 25.818181, use two floats non_repeat = 25.25 and repeat = .007
# Model
class Decimal < ActiveRecord::Base
attr_accessible :non_repeat, :repeat #both are floats
# this is approximate
def to_f
to_s.to_f
end
def to_s
"#{non_repeat + repeat}#{repeat.to_s.gsub(/0\./, '') * 3}"
end
def self.random_new
a = rand(100)
b = rand(100) / 100.0
self.new(non_repeat: a, repeat: b)
end
end
Is this a good way to randomly generate repeating decimals?
Alternately, I wasn't sure if using a random fraction is better, e.g.
Rational(rand(100), random_prime)
No comments:
Post a Comment