setScale method
Returns a BigDecimal with the specified scale.
newScale
the desired scale
Note: This is equivalent to BigDecimal.fromDouble(this.toDouble().setScale(newScale)).
BigDecimal a = BigDecimal.fromInt(42);
BigDecimal b = a.setScale(2);
print(b); // "42.00"
Implementation
BigDecimal setScale(int newScale) {
if (newScale == _scale) return this;
if (newScale > _scale) {
// Increase scale by adding zeros
int scaleDiff = newScale - _scale;
BigInt newUnscaled = _unscaledValue * BigInt.from(10).pow(scaleDiff);
return BigDecimal._(newUnscaled, newScale);
} else {
// Decrease scale by dividing and rounding
int scaleDiff = _scale - newScale;
BigInt divisor = BigInt.from(10).pow(scaleDiff);
// Simple rounding (round half up)
BigInt quotient = _unscaledValue ~/ divisor;
BigInt remainder = _unscaledValue.remainder(divisor);
BigInt halfDivisor = divisor ~/ BigInt.two;
if (remainder.abs() >= halfDivisor) {
quotient += _unscaledValue.isNegative ? BigInt.from(-1) : BigInt.one;
}
return BigDecimal._(quotient, newScale);
}
}