toHumanReadableDistanceCount static method

String toHumanReadableDistanceCount(
  1. double distance, {
  2. bool advanced = false,
  3. Locale? locale,
  4. int decimals = 2,
})

@param distance: distance in meters @param advanced: true indicates distance from millimeters to kilometers, otherwise indicates distance in meters or kilometers depending on the distance; only for metric system @param locale: indicates the user locale to get the proper unit system: metric or imperial system @param decimals: amount of decimals after float point @return formatted: distance as String

Implementation

static String toHumanReadableDistanceCount(double distance,
    {bool advanced = false, Locale? locale, int decimals = 2}) {
  bool metric = (locale ??= window.locale).usesMetricSystem;
  String unit;
  String decimalsParam = '';
  if (decimals > 0) decimalsParam = '0.';
  while (decimals-- > 0) {
    decimalsParam += '0';
  }
  if (metric) {
    if (advanced) {
      int min = 10;
      if (distance < min) return '$distance mm';
      double log10(num x) {
        num log = Math.log(x) / Math.log(10) + 0.000001;
        if ((log - log.truncate()) < 0.0001) log = log.truncateToDouble();
        return log as double;
      }

      int exp = (log10(distance) / log10(min)).truncate();
      unit = ['cm', 'dm', 'm', 'dam', 'hm', 'km'][exp - 1];
      distance /= Math.pow(min, exp);
    } else {
      if (distance < 1000) {
        unit = 'm';
      } else {
        distance /= 1000;
        unit = 'km';
      }
    }
  } else {
    if (distance < 1609.344) {
      distance *= 3.2808399;
      unit = 'ft';
    } else {
      distance /= 1609.344;
      unit = 'mi';
    }
  }
  return Intl.NumberFormat('#$decimalsParam $unit', locale.toString())
      .format(distance);
}