As mentioned earlier, simpler solutions may be based on String::replace/replaceAll + Integer.parseInt to get the integer value from the string containing suffix px:
public static int getMarginSimple(String marginPx) {
return Integer.parseInt(marginPx.replace("px", ""));
}
Another approach may use the fact that NumberFormat::parse may not use the entire text of the given string, that is, all suffixes are quietly discarded.
However, NumberFormat are not thread-safe, and a separate instance should be created per thread (e.g. using ThreadLocal):
private static final ThreadLocal<DecimalFormat> DEFAULT_FORMATTER = ThreadLocal
.withInitial(() -> new DecimalFormat());
public static int parseMargin(String margin) {
try {
return DEFAULT_FORMATTER.get().parse(margin).intValue();
} catch (ParseException pex) {
throw new IllegalArgumentException("Failed to parse " + margin, pex);
}
}
However, this would make the margins in different units "comparable":
int in2000 = parseMargin("2000in");
int mm200 = parseMargin("-200mm");
int px300 = parseMargin("300px");
System.out.printf("m1=%d, m2=%d, m3=%d%n", in2000, mm200, px300);
m1=2000, m2=-200, m3=300
Thus, the pattern should be customized to make 'px' suffix mandatory:
private static final String PIXEL_FORMAT = "#px;-#px";
private static final ThreadLocal<DecimalFormat> PIXEL_FORMATTER = ThreadLocal
.withInitial(() -> new DecimalFormat(PIXEL_FORMAT));
static int parseMarginPx(String marginPx) {
try {
return PIXEL_FORMATTER.get().parse(marginPx).intValue();
} catch (ParseException pex) {
throw new IllegalArgumentException("Failed to parse margin in pixels: " + marginPx, pex);
}
}
Then the margins in pixels are parsed and processed as follows:
int m1 = parseMarginPx("1000px");
int m2 = parseMarginPx("-1200px");
int m3 = parseMarginPx("1300px");
System.out.printf("m1=%d, m2=%d, m3=%d%n", m1, m2, m3);
if (Math.min(m2, m3) <= m1 && m1 <= Math.max(m2, m3)) {
System.out.printf("Margin m1=%dpx is between m2=%dpx and m3=%dpx%n", m1, m2, m3);
} else {
System.out.printf("Margin m1=%dpx is NOT between m2=%dpx and m3=%dpx%n", m1, m2, m3);
}
Output
m1=1000, m2=-1200, m3=1300
Margin m1=1000px is between m2=-1200px and m3=1300px