0

In the following method I need to define that only set the value if its not null and if the value is greater than "0.00" How do I define that.

 String postagePaid1 = trackInfo.getPostage();
                    if(postagePaid1 != null && ????) {
                        claim.setClPtsPostageFee(new BigDecimal(postagePaid1));
                    }
2
  • 2
    What if the string doesn't contain digits at all, or doesn't contain just digits? E.g., "foo"? Or "1.17€"? Commented Sep 22, 2014 at 16:52
  • The string only contains digits and decimal. Commented Sep 22, 2014 at 17:23

3 Answers 3

3

You can't do numeric comparisons with Strings as it doesn't make sense in the String world, only with numbers. So first check that it's not null, and if not, convert it to a double via Double.parseDouble(...)

if (someStr != null && !someStr.trim().isEmpty()) {
  try {
    double someNumber = Double.parseDouble(someStr.trim());
    if (someNumber > 0.0) {
       // ***** here you are ****
    }
  } catch (NumberFormatException nfe) { 
      // some action if String is not numeric
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Don't use String values as doubles during comparison. String comparison is done in natural order, so "1111" will be lesser than "9".

In your case, use Double.parseDouble(doubleString) and then compare values.

Comments

1

if postagePaid1 contains only double type value ,you have to convert the string to double type by using following code in order to be able to do comparison

Double.parseDouble(postagePaid1)

so if statement become :

 if(postagePaid1 != null && Double.parseDouble(postagePaid1)>0.00) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.