toDouble static method

double toDouble(
  1. dynamic value, {
  2. int? decimal,
})

Handle the value to double.

Implementation

static double toDouble(dynamic value, {int? decimal}) {
  if (value is BigInt) value = value.toString();
  if (value is double)
    return decimal == null ? value : value / pow(10, decimal);
  if (value is int)
    return decimal == null ? value.toDouble() : value / pow(10, decimal);
  if (value is String) value = value.replaceAll(',', '');
  if (value is String) {
    // Double only can handle 17 number.
    final safe = toSafeDoubleString(value);
    if (decimal == null) return double.parse(safe);
    final left = [];
    final right = [];
    for (var i = safe.length - 1; i >= 0; i--) {
      right.length < decimal ? right.add(safe[i]) : left.add(safe[i]);
    }

    if (right.length < decimal)
      right.addAll(List.filled(decimal - right.length, 0));

    final result = '0${left.reversed.join('')}.${right.reversed.join('')}';
    return double.parse(result);
  }

  return 0;
}