[Question]
  [
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 -> 44494913907563850333124661
81 / 3 -> 27
-6 / 2 -> -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 -> 0.5
3289323463 / -250000000 -> -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 -> -0.(3)
235 / 14 -> 16.7(857142)
123 / 321 -> 0.(38317757009345794392523364485981308411214953271028037)
355 / 113 -> 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)
```
---
Your program must work for all above examples in under 10 seconds on a modern desktop PC. Smallest program in bytes wins.
  
[Answer]
## 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:]>'0')
print"-%d."[x*y>=0:(t>'')+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.
[Answer]
## Batch, ~~349~~ 344 bytes
```
@echo off
set/ad=%2,i=%1/d,r=%1%%d
if not %r%==0 set i=%i%.&if %r% leq 0 set/ar=-r&if %i%==0 set i=-0.
set d=%d:-=%
set/ae=d
:g
if %r%==0 echo %i%&exit/b
set/ag=-~!(e%%2)*(!(e%%5)*4+1)
if not %g%==1 set/ae/=g&call:d&goto g
set/as=r
set i=%i%(
:r
call:d
if %r%==%s% echo %i%)&exit/b
goto r
:d
set/ar*=10,n=r/d,r%%=d
set i=%i%%n%
```
Edit: Saved 5 bytes by removing unnecessary characters. "Ungolfed":
```
@echo off
set /a d = %2
set /a i = %1 / d
set /a r = %1 % d
if not %r%==0 (
    set i=%i%.                  Decimal point is required
    if %r% leq 0 (
        set /a r = -r           Get absolute value of remainder
        if %i%==0 set i=-0.     Fix edge case (-1/3 = 0 remainder -1)
    )
)
set d = %d:-=%                  Get absolute value of divisor
set /a e = d
:g
if %r%==0 echo %i% & exit /b    Finished if there's no remainder
set /a g = gcd(e, 10)           Loop through nonrecurring decimals
if not %g%==1 (
    set /a e /= g
    call :d
    goto g
)
set /a s = r                    Save remainder to know when loop ends
set i=%i%(
:r
call :d
if %r%==%s% echo %i%)&exit/b
goto r
:d                              Add the next decimal place
set /a r *= 10
set /a n = r / d
set /a r %= d
set i=%i%%n%
```
[Answer]
# [Perl 6](http://perl6.org), ~~63 58~~ 50 bytes
```
{->$a,$b {$a~"($b)"x?$b}(|($^a.FatRat/$^b).base-repeating(10))}
```
```
{->\a,$b {a~"($b)"x?$b}(|($^a.FatRat/$^b).base-repeating)}
```
```
{$/=($^a.FatRat/$^b).base-repeating;$0~"($1)"x?$1}
```
[Test it](https://tio.run/nexus/perl6#xVLLbtswELzzK4hAaChUkrkPcskYTnPqBxQ9p1ActTDqOoYtBwnS9NfTVWQ7vrSHXqrTcjQ7s0vObtvZ@9jMp2an1edu20@N@fFo383vbjs7e3kqJjNXXLfNx7b/1PaT4vqmbG7abVdvunXX9ovVt2nhf525Asqzhw8FPL9o91WvQls7s85Y6wApRCQJGYE8JxhqnwQShSwVikhpZ5f2nJkzZ6DsJURKwRMRIMcI59UglKCikYkyInWscERqGhE4AL4JI0KYMiFxpKrG4Mdv3wTUQBDMaoZ7xaNH7RtH5YjqBhXwiENsxKUgwLj/qwtVhHDwdZQIRIJ4n4mDZKaMAYkicwo56SUkBkDgHAgFPCZPsteioE6wH4EaBwx6bxk9BcoJyfuUtC9IQFRfXS35QD6LOoGqsdqg@qeQ2IuXHDl6kJgzQPDMyCJJIvgImWP2GAOnKBhiJIGYhjFKzcB62a7s@/Eh9fj1bnN41frSFl@ssxffu0d3tVitd31Z2Yv7drnrXNE9rLt5392WtrRPutBia4couZ9H5pFyUjbrbrM0zy9/j4qd2CEswwR/jopJoDwaSCimjkPTcKjJGDgcNBzmLReKviXjlXuaC2Pqo@KYCaNTKgI8QKdxMDrvQEUYTf4xCUZDMOjDq@f/CMFv "Perl 6 – TIO Nexus")
If you don't care that it will only work with denominators that fit into a 64 bit integer it can be shortened to just 43 bytes:
```
{$/=($^a/$^b).base-repeating;$0~"($1)"x?$1}
```
### Expanded:
```
{
  # store in match variable so that we can
  # use ｢$0｣ and ｢$1｣
  $/ = (
    # turn the first value into a FatRat so that
    # it will continue to work for all Int inputs
    $^a.FatRat / $^b
  ).base-repeating;
  # ｢$0｣ is short for ｢$/[0]｣ which is the non-repeating part
  $0
  # string concatenated with
  ~
  # string repeat once if $1 is truthy (the repeating part)
  # otherwise it will be an empty Str
  "($1)" x ?$1
}
```
[Answer]
# Java, 625 605
Golfed code:
```
import static java.math.BigInteger.*;
String f(BigInteger a, BigInteger b){BigInteger[]r=a.divideAndRemainder(b);String s=r[0].toString();if(r[1].signum()<0)s="-"+s;if(!ZERO.equals(r[1])){s+='.';List<BigInteger>x=new ArrayList();List<BigInteger>y=new ArrayList();for(BigInteger d=TEN.multiply(r[1].abs());;){BigInteger[]z=d.divideAndRemainder(b.abs());int i=y.indexOf(z[1]);if(i>-1&&i==x.indexOf(z[0])){for(int j=0;j<i;++j)s+=x.get(j);s+='(';for(int j=i;j<x.size();++j)s+=x.get(j);s+=')';break;}x.add(z[0]);y.add(z[1]);if(ZERO.equals(z[1])){for(BigInteger j:x)s+=j;break;}d=TEN.multiply(z[1]);}}return s;}
```
Note: I count the static import as part of the function for golfing purposes.
This function starts out by getting the division result. It adds the integral portion and sign, if necessary. Then if there is a remainder, it performs base 10 long division. At each step, perform the division. Store the calculated digit and the remainder in two lists. If we encounter the same digit and remainder again, there is a repeated portion and we know what index it starts at. The code either adds the digits (no repeat) or the pre-repeat digits, then the repeated digits enclosed in parentheses.
This is a bit big mostly because of `BigInteger`. If the inputs did not overflow even a `long` then it could be a bit shorter. Still, I expect there are ways to improve this entry.
Ungolfed code with main method for testing:
```
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import static java.math.BigInteger.*;
public class FractionToExactDecimal {
  public static void main(String[] args) {
    // @formatter:off
    String[][] testData = new String[][] {
      { "123562375921304812375087183597", "2777", "44494913907563850333124661" },
      { "81", "3", "27" },
      { "-6", "2", "-3" },
      { "1", "2", "0.5" },
      { "3289323463", "-250000000", "-13.157293852" },
      { "-1", "3", "-0.(3)" },
      { "235", "14", "16.7(857142)" },
      { "123", "321", "0.(38317757009345794392523364485981308411214953271028037)" },
      { "355", "113", "3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)" }
    };
    // @formatter:on
    for (String[] data : testData) {
      System.out.println(data[0] + " / " + data[1]);
      System.out.println("  Expected -> " + data[2]);
      System.out.print("    Actual -> ");
      System.out.println(new FractionToExactDecimal().f(new BigInteger(data[0]), new BigInteger(data[1])));
      System.out.println();
    }
  }
  // Begin golf
  String f(BigInteger a, BigInteger b) {
    BigInteger[] r = a.divideAndRemainder(b);
    String s = r[0].toString();
    if (r[1].signum() < 0) s = "-" + s;
    if (!ZERO.equals(r[1])) {
      s += '.';
      List<BigInteger> x = new ArrayList();
      List<BigInteger> y = new ArrayList();
      for (BigInteger d = TEN.multiply(r[1].abs());;) {
        BigInteger[] z = d.divideAndRemainder(b.abs());
        int i = y.indexOf(z[1]);
        if (i > -1 && i == x.indexOf(z[0])) {
          for (int j = 0; j < i; ++j)
            s += x.get(j);
          s += '(';
          for (int j = i; j < x.size(); ++j)
            s += x.get(j);
          s += ')';
          break;
        }
        x.add(z[0]);
        y.add(z[1]);
        if (ZERO.equals(z[1])) {
          for (BigInteger j : x)
            s += j;
          break;
        }
        d = TEN.multiply(z[1]);
      }
    }
    return s;
  }
  // End golf
}
```
Program output:
```
123562375921304812375087183597 / 2777
  Expected -> 44494913907563850333124661
    Actual -> 44494913907563850333124661
81 / 3
  Expected -> 27
    Actual -> 27
-6 / 2
  Expected -> -3
    Actual -> -3
1 / 2
  Expected -> 0.5
    Actual -> 0.5
3289323463 / -250000000
  Expected -> -13.157293852
    Actual -> -13.157293852
-1 / 3
  Expected -> -0.(3)
    Actual -> -0.(3)
235 / 14
  Expected -> 16.7(857142)
    Actual -> 16.7(857142)
123 / 321
  Expected -> 0.(38317757009345794392523364485981308411214953271028037)
    Actual -> 0.(38317757009345794392523364485981308411214953271028037)
355 / 113
  Expected -> 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)
    Actual -> 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)
```
[Answer]
# PHP, 277 Bytes
```
list(,$n,$d)=$argv;$a[]=$n;$n-=$d*$r[]=$n/$d^0;!$n?:$r[]=".";while($n&&!$t){$n*=10;$n-=$d*$r[]=$n/$d^0;$t=in_array($n%=$d,$a);$a[]=$n;}if($t){$l=count($a)-($p=array_search(end($a),$a));echo join(array_slice($r,0,2+$p))."(".join(array_slice($r,2+$p,$l)).")";}else echo join($r);
```
[Answer]
# Mathematica 198 bytes
```
i=Integer;t=ToString;a_~h~b_:=f[a/b];f@q_i:= t@q;
f@q_:=""<>{t@IntegerPart[q],".",RealDigits[FractionalPart[q]][[1]]//.{{x___,{k__i}}:> {x,"("<>(t/@{k})<>")"},{x__i,j___String}:>""<> {""<>t/@{x},j}}}
```
---
## UnGolfed
```
(* hand over quotient of a, b to function f *)
h[a_, b_] := f[a/b];
(* if the quotient is an integer, return it as a string *)
f[q_Integer] := ToString@q;
(* otherwise, return the integer part, followed by a decimal point ...*)
f[q_] := "" <> {ToString@IntegerPart[q], ".", 
   (* replacing the repeating part (if it exists) between parentheses *)
   RealDigits[FractionalPart[q]][[1]] //. {{x___, {i__Integer}} :> {x, "(" <>(ToString /@ {i}) <> ")"},
   (* and the non-repeating part (if it exists) without parentheses *)
   {x__Integer, i___String} :> "" <> {"" <> ToString /@ {x}, i}}}
```
---
]