Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top