toDecimal method
Converts this BigRational to its decimal representation.
digits
The number of digits after the decimal point (default is the scale of the BigRational).
Returns a string representing the decimal value, with the specified number of digits after the decimal point.
Implementation
String toDecimal({int? digits}) {
if (digits == null && _inDecimal != null) {
return _inDecimal!;
}
digits ??= scale;
final BigInt nDive = _truncate;
final BigInt nReminder = _remainder;
String intPart = nDive.abs().toString();
final BigRational remainder = _reduce(nReminder.abs(), denominator);
final BigRational shiftedRemainder =
remainder * BigRational._(_ten.pow(digits), _one);
final BigInt decPart =
shiftedRemainder.numerator ~/ shiftedRemainder.denominator;
if (isNegative) {
intPart = "-$intPart";
}
if (decPart == _zero) {
return intPart;
}
String decPartStr = decPart.abs().toString();
if (decPartStr.length < digits) {
decPartStr = '0' * (digits - decPartStr.length) + decPartStr;
}
if ((shiftedRemainder.numerator % shiftedRemainder.denominator) == _zero) {
while (decPartStr.endsWith('0')) {
decPartStr = decPartStr.substring(0, decPartStr.length - 1);
}
}
if (digits < 1) {
return intPart;
}
return '$intPart${decPart < _zero ? '' : '.'}$decPartStr';
}