diff options
Diffstat (limited to 'src/cgeo/geocaching/geopoint/DistanceParser.java')
| -rw-r--r-- | src/cgeo/geocaching/geopoint/DistanceParser.java | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/src/cgeo/geocaching/geopoint/DistanceParser.java b/src/cgeo/geocaching/geopoint/DistanceParser.java new file mode 100644 index 0000000..3578902 --- /dev/null +++ b/src/cgeo/geocaching/geopoint/DistanceParser.java @@ -0,0 +1,47 @@ +package cgeo.geocaching.geopoint; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import cgeo.geocaching.cgBase; +import cgeo.geocaching.cgSettings; + +public final class DistanceParser { + + private static final Pattern pattern = Pattern.compile("^([0-9\\.\\,]+)[ ]*(m|km|ft|yd|mi|)?$", Pattern.CASE_INSENSITIVE); + + /** + * Parse a distance string composed by a number and an optional suffix + * (such as "1.2km"). + * + * @param distanceText the string to analyze + * @return the distance in kilometers + * + * @throws NumberFormatException if the given number is invalid + */ + public static double parseDistance(String distanceText, final int defaultUnit) { + final Matcher matcher = pattern.matcher(distanceText); + + if (!matcher.find()) { + throw new NumberFormatException(distanceText); + } + + final double value = Double.parseDouble(matcher.group(1)); + final String unit = matcher.group(2).toLowerCase(); + + if (unit.equals("m") || (unit.length() == 0 && defaultUnit == cgSettings.unitsMetric)) { + return value / 1000; + } + if (unit.equals("km")) { + return value; + } + if (unit.equals("yd")) { + return value * cgBase.yards2km; + } + if (unit.equals("mi")) { + return value * cgBase.miles2km; + } + return value * cgBase.feet2km; + } + +} |
