1

I have the following conundrum. In C#, I want to store a rational and get a string representation of it's decimal notation.

Normally I would just use float or double to store the number and get the string but I would like a "high resolution" decimal notation. The double data type only gives about 16 characters at best in it's string representation. I am looking for the string representation of the decimal notation to contain many more characters, around 30-50 would be ideal. I need the "high resolution" to check for repeating sub-sequences.

The rational number might be simple but I would like the string representation to be very detailed

Example: 1/7 => 0.1428571428571428571428571428

My Question: Is there a C# data structure in the .NET libraries that will store and print rational numbers like I described above?

recursion.ninja
  • 5,377
  • 7
  • 46
  • 78

2 Answers2

3

The Base Class Library's CodePlex site contains a BigRational type, which provides " an arbitrary-precision rational number type." This should provide the detail and precision you wish.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • I'm slightly new to C#, I have downloaded the BigRational library and refferenced the `BigRationalLibrary.dll` file in my IDE. I don't know how to include the library with the `using` statement. What is the BigRationalLibrary's namespace? – recursion.ninja Aug 28 '12 at 05:32
  • The documentation is your friend. – mbm Aug 28 '12 at 05:43
  • @awashburn You'd add `using Numerics;` – Reed Copsey Aug 28 '12 at 17:34
  • I confused `using System.Numerics;` with `using Numerics;`. My frustrations are now gone! – recursion.ninja Aug 30 '12 at 13:29
  • It also has some known bugs. See the issues on the CodePlex site. – Sam Dec 05 '13 at 03:56
  • I just tried this out, and `BigRational` doesn't seem to even provide a method to format the number using decimal notation. In the example in the question, it displays `1/7` as *1/7*, and I couldn't find any way to format it differently. – Sam Dec 05 '13 at 04:25
  • It also seems to be available on NuGet: [BigRationalLibrary](https://www.nuget.org/packages/BigRationalLibrary/). – dharmatech Aug 04 '15 at 20:44
0

The only existing work I could find with this functionality was the Rational class provided by Ken Johnson.

Here's an example to achieve what you wanted:

[TestMethod]
public void FormatsAsDecimal()
{
    var oneSeventh = new Rational(1, 7);
    var oneSeventhAsDecimal = oneSeventh.ToString(EApproxmationType.DecimalPlaces, 28, true);
    oneSeventhAsDecimal.Should().Be("0.1428571428571428571428571428");
}
Sam
  • 40,644
  • 36
  • 176
  • 219