Editor

Fraction to Recurring Decimal

#154 · Math · Advanced · 140 XP · about 30 min

Some fractions have short decimals (1/4 = 0.25), and others repeat forever (1/3 = 0.333...). A repeating decimal can still be written exactly by putting the repeating block in parentheses: 1/3 is 0.(3) and 1/6 is 0.1(6).

Write fraction_to_decimal(numerator, denominator) that returns the exact decimal of numerator / denominator as a string:

  • If the result is a whole number, return it without a decimal point ('2', '-3', '0').
  • Otherwise write the whole part, a ., then the digits after the point, with the repeating block (if there is one) in parentheses. Use the shortest repeating block, starting as early as possible.
  • Put a - in front when the result is negative.

Examples

fraction_to_decimal(1, 4)      # returns '0.25'
fraction_to_decimal(4, 333)    # returns '0.(012)'
fraction_to_decimal(-22, 7)    # returns '-3.(142857)'
fraction_to_decimal(6, -3)     # returns '-2'

4/333 = 0.012012012..., so the block 012 repeats from the first digit after the point.

Constraints

  • -2^31 <= numerator, denominator <= 2^31 - 1
  • denominator is never 0
  • The answer is always shorter than 10,000 characters

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.