aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/geopoint/DistanceParser.java
diff options
context:
space:
mode:
authorSamuel Tardieu <sam@rfc1149.net>2011-09-16 14:36:28 +0200
committerSamuel Tardieu <sam@rfc1149.net>2011-09-16 14:36:28 +0200
commit579ef7a535489d4aa632db11667a3b01deb6cafd (patch)
tree55810021c02ac7d80d3a9702ef0b59e4af154b9c /main/src/cgeo/geocaching/geopoint/DistanceParser.java
parent96ea21fd50334479c262da692038965d0e4d596a (diff)
downloadcgeo-579ef7a535489d4aa632db11667a3b01deb6cafd.zip
cgeo-579ef7a535489d4aa632db11667a3b01deb6cafd.tar.gz
cgeo-579ef7a535489d4aa632db11667a3b01deb6cafd.tar.bz2
Move sources into the main directory
This prepares the inclusion of tests into the same repository.
Diffstat (limited to 'main/src/cgeo/geocaching/geopoint/DistanceParser.java')
-rw-r--r--main/src/cgeo/geocaching/geopoint/DistanceParser.java49
1 files changed, 49 insertions, 0 deletions
diff --git a/main/src/cgeo/geocaching/geopoint/DistanceParser.java b/main/src/cgeo/geocaching/geopoint/DistanceParser.java
new file mode 100644
index 0000000..a48d347
--- /dev/null
+++ b/main/src/cgeo/geocaching/geopoint/DistanceParser.java
@@ -0,0 +1,49 @@
+package cgeo.geocaching.geopoint;
+
+import cgeo.geocaching.cgBase;
+import cgeo.geocaching.cgSettings;
+
+import java.util.regex.Matcher;
+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 int defaultUnit) {
+ final Matcher matcher = pattern.matcher(distanceText);
+
+ if (!matcher.find()) {
+ throw new NumberFormatException(distanceText);
+ }
+
+ final float value = Float.parseFloat(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;
+ }
+
+}