convert method

UcumDecimal convert(
  1. UcumDecimal value,
  2. String sourceUnit,
  3. String destUnit
)

Implementation

UcumDecimal convert(UcumDecimal value, String sourceUnit, String destUnit) {
  assert(checkStringParam(sourceUnit),
      paramError('convert', 'sourceUnit', 'must not be null or empty'));
  assert(checkStringParam(destUnit),
      paramError('convert', 'destUnit', 'must not be null or empty'));

  if (sourceUnit == destUnit) {
    return value;
  }

  final Canonical src = Converter(model, handlers)
      .convert(ExpressionParser(model).parse(sourceUnit));
  final Canonical dst = Converter(model, handlers)
      .convert(ExpressionParser(model).parse(destUnit));
  final String s = ExpressionComposer().composeCanonical(src, false);
  final String d = ExpressionComposer().composeCanonical(dst, false);

  if (s != d) {
    throw UcumException(
        'Unable to convert between units $sourceUnit and $destUnit as they do not have matching canonical forms ($s and $d respectively)');
  }

  final UcumDecimal canValue = value.multiply(src.value);
  final UcumDecimal res = canValue.divide(dst.value);

  if (value.isWholeNumber()) {
    res.checkForCouldBeWholeNumber();
  }

  return res;
}