BigDecimal.parse constructor

BigDecimal.parse(
  1. String value
)

Implementation

factory BigDecimal.parse(String value) {
  var sign = '';
  var index = 0;
  var nextIndex = 0;

  switch (value.codeUnitAt(index)) {
    case minusCode:
      sign = '-';
      index++;
      break;
    case plusCode:
      index++;
      break;
    default:
      break;
  }

  nextIndex = nextNonDigit(value, index);
  final integerPart = '$sign${value.substring(index, nextIndex)}';
  index = nextIndex;

  if (index >= value.length) {
    return BigDecimal.fromBigInt(BigInt.parse(integerPart));
  }

  var decimalPart = '';
  if (value.codeUnitAt(index) == dotCode) {
    index++;
    nextIndex = nextNonDigit(value, index);
    decimalPart = value.substring(index, nextIndex);
    index = nextIndex;

    if (index >= value.length) {
      return BigDecimal._(
        intVal: BigInt.parse('$integerPart$decimalPart'),
        scale: decimalPart.length,
      );
    }
  }

  switch (value.codeUnitAt(index)) {
    case smallECode:
    case capitalECode:
      index++;
      final exponent = int.parse(value.substring(index));
      return BigDecimal._(
        intVal: BigInt.parse('$integerPart$decimalPart'),
        scale: decimalPart.length - exponent,
      );
  }

  throw Exception(
    'Not a valid BigDecimal string representation: $value.\n'
    'Unexpected ${value.substring(index)}.',
  );
}