Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,943 questions

55,787 answers

573 users

How to convert a decimal number to a rational number in Ruby

1 Answer

0 votes
#
# convert_decimal_to_rational(s)
# ------------------------------
# Converts a decimal number (given as a string) into an exact Rational p/q.
#
# Why Ruby makes this easy:
#   • Ruby has a built‑in Rational class.
#   • Rational() can convert strings exactly.
#   • It avoids floating‑point inaccuracies by parsing the string directly.
#
# Algorithm (handled internally by Rational()):
#   1. Parse the string.
#   2. Convert integer and fractional parts into numerator/denominator.
#   3. Reduce using gcd.
#

def convert_decimal_to_rational(s)
  # Rational(s) interprets the string exactly, avoiding float rounding issues.
  Rational(s)
end

def main
  values = [
    "3.5", "12.75", "0.125", "100.001",
    "7", "42.0", "0.333", "5.2"
  ]

  values.each do |v|
    r = convert_decimal_to_rational(v)
    puts "#{v} -> #{r.numerator}/#{r.denominator}"
  end
end

main



=begin
run:

3.5 -> 7/2
12.75 -> 51/4
0.125 -> 1/8
100.001 -> 100001/1000
7 -> 7/1
42.0 -> 42/1
0.333 -> 333/1000
5.2 -> 26/5

=end

 



answered Jul 23 by avibootz

Related questions

...