diff options
| author | Bananeweizen <bananeweizen@gmx.de> | 2014-11-02 11:07:28 +0100 |
|---|---|---|
| committer | Bananeweizen <bananeweizen@gmx.de> | 2014-11-02 11:07:28 +0100 |
| commit | 7c95d28947a9ed8f003bfaef147f2fb72dc4b6ab (patch) | |
| tree | d1c1abf0ff3bb2b0d2296ca185a634d0c6ebcea5 /main/src/cgeo/geocaching/location/DistanceParser.java | |
| parent | 5dadcf6d74d5d73b6beb3883df219b69a2c337fb (diff) | |
| download | cgeo-7c95d28947a9ed8f003bfaef147f2fb72dc4b6ab.zip cgeo-7c95d28947a9ed8f003bfaef147f2fb72dc4b6ab.tar.gz cgeo-7c95d28947a9ed8f003bfaef147f2fb72dc4b6ab.tar.bz2 | |
rename package
The package not only contains the GeoPoint definition, but other
location related classes, too.
Diffstat (limited to 'main/src/cgeo/geocaching/location/DistanceParser.java')
| -rw-r--r-- | main/src/cgeo/geocaching/location/DistanceParser.java | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/main/src/cgeo/geocaching/location/DistanceParser.java b/main/src/cgeo/geocaching/location/DistanceParser.java new file mode 100644 index 0000000..1fb8fc7 --- /dev/null +++ b/main/src/cgeo/geocaching/location/DistanceParser.java @@ -0,0 +1,51 @@ +package cgeo.geocaching.location; + +import cgeo.geocaching.utils.MatcherWrapper; + +import org.apache.commons.lang3.StringUtils; + +import java.util.Locale; +import java.util.regex.Pattern; + +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 float parseDistance(String distanceText, final boolean metricUnit) + throws NumberFormatException { + final MatcherWrapper matcher = new MatcherWrapper(pattern, distanceText); + + if (!matcher.find()) { + throw new NumberFormatException(distanceText); + } + + final float value = Float.parseFloat(matcher.group(1).replace(',', '.')); + final String unit = matcher.group(2).toLowerCase(Locale.US); + + if (unit.equals("m") || (StringUtils.isEmpty(unit) && metricUnit)) { + return value / 1000; + } + if (unit.equals("km")) { + return value; + } + if (unit.equals("yd")) { + return value * IConversion.YARDS_TO_KILOMETER; + } + if (unit.equals("mi")) { + return value * IConversion.MILES_TO_KILOMETER; + } + return value * IConversion.FEET_TO_KILOMETER; + } + +} |
