Home > Blockchain >  Compare Numeric Values inside String in JAVA
Compare Numeric Values inside String in JAVA

Time:10-18

I have the following two strings:

String margin1 = "-1100px";
String margin2 = "-1000px";
String margin3 = "-1300px";

Could someone help me to compare make condition based on the numerical values inside the String? for example:

if (/*Numerical value of*/ margin1 /*is between*/ margin2 /*and*/ margin3)
       break;

Thank you in advance for your help.

CodePudding user response:

You can use Integer.parseInt and String.replace. You can do it like this

if( 
        Integer.parseInt(margin1.replace("px","")) >= Integer.parseInt(margin2.replace("px","")) 
        && Integer.parseInt(margin1.replace("px","")) <= Integer.parseInt(margin3.replace("px",""))
        )
break;

CodePudding user response:

There can be many ways to do it. Given below is a way by parsing the given strings with the help of ParsePosition and then comparing the numerical values:

import java.text.NumberFormat;
import java.text.ParsePosition;

public class Main {
    public static void main(String[] args) {
        String margin1 = "-1100px";
        String margin2 = "-1000px";
        String margin3 = "-1300px";

        NumberFormat formatter = NumberFormat.getInstance();

        int intMargin1 = formatter.parse(margin1, new ParsePosition(0)).intValue();
        int intMargin2 = formatter.parse(margin2, new ParsePosition(0)).intValue();
        int intMargin3 = formatter.parse(margin3, new ParsePosition(0)).intValue();

        if ((intMargin1 > intMargin2 && intMargin1 < intMargin3)
                || (intMargin1 < intMargin2 && intMargin1 > intMargin3))
            System.out.println(margin1   " is between "   margin2   " and "   margin3);
        else
            System.out.println(margin1   " is between "   margin2   " and "   margin3);
    }
}

Output:

-1100px is between -1000px and -1300px

ONLINE DEMO

CodePudding user response:

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

CodePudding user response:

I would use a regex to extract the model (- or ) the second one (integer) and the last one (px) You can use this regex on your java code : [ |-]?[0-9] px$ you can test it here : https://www.freeformatter.com/java-regex-tester.html#ad-output

private static final Pattern p = Pattern.compile("^[ |-]?[0-9] px$");

private int parseCssToken(String token){
Matcher m = p.matcher(token); // token = "-1200px"
if (m.find()) {
        // ...then you can use group() methods.
        return Integer.parseInt(m.group(1)); // this will extract 1200
    }
// throw Exception here if you don't have any match
}
:
:
// further, you can use your method like this :

if (parseCssToken(margin1) >= parseCssToken(margin2) && 
parseCssToken(margin1) <= parseCssToken(margin3)){
// your logic here
:
}

  • Related