Editor

Decimal to Fraction

#364 · Math · Advanced · 130 XP · about 25 min

A decimal that repeats forever can be written exactly by putting the repeating block in parentheses: 1/3 is 0.(3), 1/6 is 0.1(6) and 22/7 is 3.(142857). Every decimal like that is a fraction, and the trip back is a neat piece of algebra.

Write to_fraction(s) that takes a decimal string and returns its exact value as a string 'p/q' in lowest terms, with q positive and the minus sign, if any, on p. Whole numbers end in /1, and zero is '0/1'.

The string s is made of:

  • an optional - sign
  • one or more digits (the whole part)
  • optionally a ., then zero or more digits that do not repeat, then optionally a repeating block of one or more digits in parentheses. When there is a ., at least one digit follows it, inside or outside the parentheses.

Examples

to_fraction('0.75')       # returns '3/4'
to_fraction('0.(3)')      # returns '1/3'
to_fraction('-0.1(6)')    # returns '-1/6'
to_fraction('0.(9)')      # returns '1/1'

0.999... with the 9s going on forever is exactly 1.

Constraints

  • s has at most 60 characters
  • s is never a negative zero such as '-0.0'

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.