Clucking Turtle
Clucking Turtle

Reputation: 922

Represent repeating decimals in Rails model

What's a good way to represent repeating decimals in the database?

Example 2.818181, the 81 repeats

Idea 1

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

Idea 2

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

Answers (2)

Dan Rey Oquindo
Dan Rey Oquindo

Reputation: 276

rand = rand(100)

3.times { print rand.to_s }

Upvotes: 0

Save
Save

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:

  • Randomly generate the integer part of your repeating number
  • Generate another random integer, rapresenting the repetition
  • Transform those 2 numbers into a fraction using the usual formula

Upvotes: 1

Related Questions