toStringAsPrecision method
A string representation with precision significant digits.
Implementation
String toStringAsPrecision(int precision) {
assert(precision > 0);
if (this == zero) {
return <String>[
'0',
if (precision > 1) '.',
for (var i = 1; i < precision; i++) '0',
].join();
}
final limit = ten.pow(precision).toDecimal();
var shift = one;
final absValue = abs();
var pad = 0;
while (absValue * shift < limit) {
pad++;
shift *= ten;
}
while (absValue * shift >= limit) {
pad--;
shift = (shift / ten).toDecimal();
}
final value = ((this * shift).round() / shift).toDecimal();
// Rounding can carry into a new power of 10 (e.g. `9.99` with precision 2
// rounds to `10`). That adds an integer digit, so one fewer fractional
// digit is needed to keep exactly [precision] significant digits.
if (value.abs() * shift >= limit) {
pad--;
}
return pad <= 0 ? value.toString() : value.toStringAsFixed(pad);
}