aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/geopoint/DistanceParser.java
blob: 5f02895d31844a46b021a7595fd33dc27cbffec1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package cgeo.geocaching.geopoint;

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 boolean metricUnit) {
        final Matcher matcher = pattern.matcher(distanceText);

        if (!matcher.find()) {
            throw new NumberFormatException(distanceText);
        }

        final float value = Float.parseFloat(matcher.group(1).replace(',', '.'));
        final String unit = matcher.group(2).toLowerCase();

        if (unit.equals("m") || (unit.length() == 0 && 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;
    }

}