fromReadable method

double? fromReadable()

Parses a readable number string with K, M, B, T suffixes to a double. Automatically handles K (thousand), M (million), B (billion), T (trillion).

Example:

String text = '1.5K';
double? value = text.fromReadable(); // 1500.0
'1.5M'.fromReadable(); // 1500000.0
'1.5B'.fromReadable(); // 1500000000.0
'1.5T'.fromReadable(); // 1500000000000.0

Implementation

double? fromReadable() {
  if (isEmpty) return null;

  // Remove whitespace and convert to uppercase for case-insensitive matching
  final cleaned = trim().toUpperCase();

  // Check for negative sign
  final isNegative = cleaned.startsWith('-');
  final positiveValue = isNegative ? cleaned.substring(1) : cleaned;

  // Remove any non-numeric characters except decimal point and suffix letters
  final numberPart = positiveValue.replaceAll(RegExp(r'[^0-9.]'), '');
  if (numberPart.isEmpty) return null;

  // Try to parse the base number
  final baseValue = double.tryParse(numberPart);
  if (baseValue == null) return null;

  // Check for suffix (K, M, B, T)
  if (positiveValue.endsWith('K')) {
    return (isNegative ? -1 : 1) * baseValue * 1000;
  } else if (positiveValue.endsWith('M')) {
    return (isNegative ? -1 : 1) * baseValue * 1000000;
  } else if (positiveValue.endsWith('B')) {
    return (isNegative ? -1 : 1) * baseValue * 1000000000;
  } else if (positiveValue.endsWith('T')) {
    return (isNegative ? -1 : 1) * baseValue * 1000000000000;
  }

  // No suffix, return as-is
  return isNegative ? -baseValue : baseValue;
}