mantissaCorrection function

String mantissaCorrection(
  1. double value,
  2. int significantFigures,
  3. bool removeTrailingZeros
)

Given a double value it returns its rapresentation as a string with few tweaks: significantFigures is the number of significant figures to keep, removeTrailingZeros say if non important zeros should be removed, e.g. 1.000000 --> 1

Implementation

String mantissaCorrection(double value, int significantFigures, bool removeTrailingZeros) {
  //Round to a fixed number of significant figures
  var stringValue = value.toStringAsPrecision(significantFigures);
  var append = '';

  //if the user want to remove the trailing zeros
  if (removeTrailingZeros) {
    //remove exponential part and append to the end
    if (stringValue.contains('e')) {
      append = 'e' + stringValue.split('e')[1];
      stringValue = stringValue.split('e')[0];
    }

    //remove trailing zeros (just fractional part)
    if (stringValue.contains('.')) {
      var firstZeroIndex = stringValue.length;
      for (; firstZeroIndex > stringValue.indexOf('.'); firstZeroIndex--) {
        var charAtIndex = stringValue.substring(firstZeroIndex - 1, firstZeroIndex);
        if (charAtIndex != '0' && charAtIndex != '.') break;
      }
      stringValue = stringValue.substring(0, firstZeroIndex);
    }
  }
  return stringValue + append; //append exponential part
}