Fraction to exact decimal Write a program or function that given two integers a, b outputs a string containing a decimal number representing the fraction a/b exactly.

If a/b is integer, simply output the value, without a decimal dot or leading zeroes:

123562375921304812375087183597 / 2777 -&gt; 44494913907563850333124661
81 / 3 -&gt; 27
-6 / 2 -&gt; -3


If a/b is not integer but has a finite representation in base 10, output the value without leading or trailing zeroes (except a single zero before the dot):

1 / 2 -&gt; 0.5
3289323463 / -250000000 -&gt; -13.157293852


Finally, if and only if (so no 0.999...) a/b is not integer and does not have a finite representation, output the finite part followed by the repeating part in parenthesis. The repeating part must be as small as possible, and start as early as possible.

-1 / 3 -&gt; -0.(3)
235 / 14 -&gt; 16.7(857142)
123 / 321 -&gt; 0.(38317757009345794392523364485981308411214953271028037)
355 / 113 -&gt; 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)




Your program must work for all above examples in under 10 seconds on a modern desktop PC. Smallest program in bytes wins.
Python 2, 174 bytes

x,y=input()
a=abs(x)
b=abs(y)
r=a%b*10
L=[]
M=''
while~-(r in L):L+=r,;M+=str(r/b);r=r%b*10
i=L.index(r)
t=M[:i]+"(%s)"%M[i:]*(M[i:]&gt;'0')
print"-%d."[x*y&gt;=0:(t&gt;'')+3]%(a/b)+t


I'm not quite convinced about the validity of this answer, but it's worked for the test cases above and other test cases I've thrown at it. It looks like a right mess though, so I'm sure there's plenty of room for golfing.

The initial setup takes absolute values of both arguments to ensure that we're dealing with nonnegative numbers (saving the sign calculation for later), and delegates the quotient part of the result to Python's arbitrary precision arithmetic. The fractional part is done with the grade-school division algorithm until we get a repeat in the remainder. We then look up when we last saw this repeat in order to get the period, and construct the string accordingly.

Note that the algorithm's actually quite slow due to the O(n) in operation, but it's fast enough for the examples.