throws MeasurementConversionException {
input = input.replaceAll("\\s", ""); // our pattern assumes no whitespace
Matcher matcher = NUMBER_OPTIONAL_UNIT_PATTERN.matcher(input);
if (!matcher.matches()) {
throw new MeasurementConversionException("The passed input '" + input + "' could not be parsed correctly "
+ "by the regular expression " + NUMBER_OPTIONAL_UNIT_PATTERN_STRING);
}
String magnitude = matcher.group(1);
String units = matcher.group(2);
MeasurementUnits fromUnits;
if (units.equals("")) {
/*
* no units is valid, and we assume the passed targetUnits; however, we will
* still need to check that the number is well-formed, so continue processing.
*/
fromUnits = targetUnits;
} else {
fromUnits = MeasurementUnits.getUsingDisplayUnits(units, targetUnits.getFamily());
if ((fromUnits == null) || (!fromUnits.isComparableTo(targetUnits))) {
throw new MeasurementConversionException("The units in '" + input + "' were not valid, " + "expected '"
+ targetUnits.getFamily() + "' units, received '" + units + "' units");
}
}
try {
if (magnitude.startsWith("+")) {
magnitude = magnitude.substring(1);
}
Number convertedMagnitude = DecimalFormat.getInstance().parse(magnitude);
Double scaledMagnitude;
// apply relative scale if applicable, otherwise perform standard scaling
if (MeasurementUnits.Family.RELATIVE == targetUnits.getFamily()) {
scaledMagnitude = MeasurementUnits.scaleDown(convertedMagnitude.doubleValue(), targetUnits);
} else {
MeasurementNumericValueAndUnits valueAndUnits = new MeasurementNumericValueAndUnits(convertedMagnitude
.doubleValue(), fromUnits);
scaledMagnitude = MeasurementConverter.scale(valueAndUnits, targetUnits);
}
return new MeasurementNumericValueAndUnits(scaledMagnitude, targetUnits);
} catch (ParseException pe) {
throw new MeasurementConversionException("The magnitude in '" + input + "' did not parse correctly "
+ "as a valid, localized, stringified number ");
}
}