Decimal.parse constructor

Decimal.parse(
  1. String value
)

Parse from string

Examples:

  • "2" -> 2
  • "0.2" -> 0.2
  • "-0.2000" -> -0.2000
  • ".0" -> 0.0
  • "-.25" -> -0.25
  • "1." -> 1
  • "-0." -> 0
  • "+.230" -> 0.230
  • "1/3" -> Rational(1, 3)

Implementation

factory Decimal.parse(String value) {
  value = value.trim();
  if (value.isEmpty) {
    throw FormatException('Empty string cannot be parsed as Decimal');
  }
  if (value.contains("/")) {
    return Rational.parse(value);
  }

  final isNegative = value.startsWith('-');
  if (isNegative || value.startsWith('+')) {
    value = value.substring(1);
  }

  final parts = value.split('.');
  if (parts.length > 2) {
    throw FormatException('Invalid decimal format: $value');
  }

  final integerPart = parts[0];
  final fractionalPart = parts.length == 2 ? parts[1] : '';
  final scale = fractionalPart.length;

  final integer = _parseBigInt(integerPart);
  final fractional = _parseBigInt(fractionalPart);
  final totalValue = integer * pow10(scale) + fractional;

  return Decimal(isNegative ? -totalValue : totalValue, scale);
}