2016-07-14 01:46:44 +02:00
|
|
|
package fr.pandacube.java.util.measurement;
|
|
|
|
|
|
|
|
import java.text.DecimalFormat;
|
|
|
|
import java.util.Arrays;
|
|
|
|
|
|
|
|
public class DistanceUtil {
|
|
|
|
|
|
|
|
public static String distanceToString(double meterDist, int precision, DistanceUnit... desiredUnits) {
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-07-14 01:46:44 +02:00
|
|
|
Arrays.sort(desiredUnits);
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-07-14 01:46:44 +02:00
|
|
|
DistanceUnit choosenUnit = desiredUnits[0]; // la plus petite unitée
|
|
|
|
for (DistanceUnit unit : desiredUnits) {
|
2016-07-14 14:22:23 +02:00
|
|
|
if (meterDist / unit.multiplicator < 1) continue;
|
2016-07-14 01:46:44 +02:00
|
|
|
choosenUnit = unit;
|
|
|
|
}
|
2016-07-14 14:22:23 +02:00
|
|
|
|
|
|
|
if (choosenUnit != desiredUnits[0] && precision <= 2) precision = 2;
|
|
|
|
|
2016-07-14 01:46:44 +02:00
|
|
|
String precisionFormat = "##0";
|
2016-07-14 14:22:23 +02:00
|
|
|
if (precision > 0) precisionFormat += ".";
|
|
|
|
for (int i = 0; i < precision; i++)
|
2016-07-14 01:46:44 +02:00
|
|
|
precisionFormat += "0";
|
|
|
|
DecimalFormat df = new DecimalFormat(precisionFormat);
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-07-14 01:46:44 +02:00
|
|
|
double dist = meterDist / choosenUnit.multiplicator;
|
2016-07-14 14:22:23 +02:00
|
|
|
|
|
|
|
return df.format(dist) + choosenUnit.unitStr;
|
2016-07-14 01:46:44 +02:00
|
|
|
}
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-07-14 01:46:44 +02:00
|
|
|
public static String distanceToString(double meterDist, int precision) {
|
|
|
|
return distanceToString(meterDist, precision, DistanceUnit.M, DistanceUnit.KM);
|
|
|
|
}
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-07-14 01:46:44 +02:00
|
|
|
public enum DistanceUnit implements Comparable<DistanceUnit> {
|
2016-07-14 14:22:23 +02:00
|
|
|
NM(0.000000001, "nm"), µM(0.000001, "µm"), MM(0.001, "mm"), CM(0.01, "cm"), M(1, "m"), KM(1000, "km");
|
|
|
|
|
2016-07-14 01:46:44 +02:00
|
|
|
private final double multiplicator;
|
|
|
|
private final String unitStr;
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-07-14 01:46:44 +02:00
|
|
|
private DistanceUnit(double mult, String s) {
|
|
|
|
multiplicator = mult;
|
|
|
|
unitStr = s;
|
|
|
|
}
|
|
|
|
}
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-07-14 01:46:44 +02:00
|
|
|
}
|