Before you read, please be aware that I'm aware of the differences between integer and floating-point division, and I'm aware of how BigInteger.DivRem
and BigInteger.Divide
.
Consider the following code examples:
BigInteger a = new(5);
BigInteger b = new(2);
BigInteger div = BigInteger.DivRem(a, b, out BigInteger rem);
Console.WriteLine($"{div}.{rem}");
Output = 2.1
BigInteger a = new(5678);
BigInteger b = new(1234);
BigInteger div = BigInteger.DivRem(a, b, out BigInteger rem);
Console.WriteLine($"{div}.{rem}");
Output = 4.742
Neither of the outputs is correct (in the context of what I'm asking). Sure, they're correct in the sense that they're displaying a division and a remainder formatted as ${div}.{rem}
, but in my case, that's not what I'm looking for.
The correct values would be 2.5
and 4.6012965964
(with a scale of 10 digits) respectively.
Is there a way to convert/represent the remainder as a fractional value, rather than as a remainder?
Note: I know there is float
, double
and decimal
, but those aren't the solution I'm looking for.
CodePudding user response:
This seems to work:
BigInteger a = new(5678);
BigInteger b = new(1234);
BigInteger div = BigInteger.DivRem(a, b, out BigInteger rem);
var decimalDigits = new List<BigInteger>();
while (rem != 0 && decimalDigits.Count < 10)
{
rem *= 10;
decimalDigits.Add(BigInteger.DivRem(rem, b, out rem));
}
Console.WriteLine($"{div}.{string.Concat(decimalDigits)}");
This is pretty much just an implementation of long division.
CodePudding user response:
You have misunderstood - what you are doing is integer arithmetic on big integers and the results are correct. Read here Math.DivRem() (to understand DIV and REM as concepts, forget about integral type for now).
What you seem to be after is a floating point type with precision greater than double
. Last time I looked no such type exists in .Net, except for a few privateer efforts like QPFloat