Just do a long high school split:
int value = 1; bool outputDecimalSeparator = false; int digitsOutput = 1; while(digitsOutput <= k) { if (value == 0) { Console.Write(0); } else { if (value < n) { Console.Write(0); value *= 10; } else { Console.Write(value / n); value %= n; } } if (outputDecimalSeparator == false) { outputDecimalSeparator = true; Console.Write('.'); } digitsOutput++; } Console.WriteLine();
The branch on value == 0 should detect when 1 / n has a final representation less than k .
Here n is the denominator in 1 / n , and k is the number of digits to be printed in decimal 1 / n .
Note that by changing value *= 10 to value *= b , you can also print a b-ary representation of 1 / n .
jason
source share