format method

  1. @override
String format(
  1. dynamic value
)

value is expected to be a Quantity, Number or num object.

Implementation

@override
String format(dynamic value) {
  String? realStr;
  String? imagStr;
  if (value is num) {
    realStr = value.toString();
  } else {
    final number = value is Number
        ? value
        : value is Quantity
            ? value.valueSI
            : null;
    if (number is Integer) {
      realStr = number.toInt().toString();
    } else if (number is Double) {
      realStr = number.toDouble().toString();
    } else if (number is Imaginary) {
      imagStr = number.value.toString();
    } else if (number is Complex) {
      if (number.real.value.toDouble() != 0) {
        realStr = number.real.isInteger == true ? '${number.real.toInt()}' : number.real.toString();
      }
      if (number.imag.value.toDouble() != 0) {
        imagStr = number.imag.value.isInteger == true ? '${number.imag.value.toInt()}' : number.imag.value.toString();
      }
      if (realStr == null && imagStr == null) realStr = '0';
    } else if (number is Precise) {
      realStr = number.toString();
    }
  }

  if (realStr?.isNotEmpty == true) realStr = adjustForExponent(realStr!);
  if (imagStr?.isNotEmpty == true) imagStr = adjustForExponent(imagStr!);

  final buf = StringBuffer();
  if (realStr?.isNotEmpty == true) buf.write(insertSpaces(realStr!));
  if (imagStr?.isNotEmpty == true) {
    if (buf.isNotEmpty) {
      if (imagStr?.startsWith('-') == true) {
        buf.write(' - ');
        imagStr = imagStr!.substring(1);
      } else {
        buf.write(' + ');
      }
    }
    final s = insertSpaces(imagStr!);
    final expIndex = _exponentIndex(s);
    if (expIndex == -1) {
      buf..write(s)..write('i');
    } else {
      buf..write(s.substring(0, expIndex))..write('i')..write(s.substring(expIndex));
    }
  }

  return buf.toString();
}