Reputation: 922
What's a good way to represent repeating decimals in the database?
Example 2.818181
, the 81
repeats
Separate 2.818181
into non-repeating and repeating parts, then non_repeat = 2.0
and repeat = .007
class Decimal < ActiveRecord::Base
attr_accessible :non_repeat, :repeat #floats
def to_f
to_s.to_f
end
def to_s
"#{non_repeat + repeat}#{repeat.to_s.gsub(/0\./, '') * 3}" #approximation
end
def self.random_new
a = rand(100)
b = rand(100) / 100.0
self.new(non_repeat: a, repeat: b)
end
end
Use a fraction, which means turn 2.818181
into 31/11
, save two integers 31
and 11
class Decimal < ActiveRecord::Base
attr_accessible :numerator, :denominator #integers
def to_f
numerator / denominator
end
def to_s
to_f.to_s
end
def self.random_new
a = rand(100)
b = random_prime(...) # like 7, 9, 11
self.new(numerator: a, denominator: b)
end
end
For the purpose of randomly generating repeating decimals, which idea is better? Or is there another way?
Upvotes: 1
Views: 370
Reputation: 11938
Your second approach won't always generate a repeating decimal number, just think what happens if a is a multiple of b.
The idea of using fractions tho is the best one. You need to slightly change your approach:
Upvotes: 1