I have the following code in Java;
BigDecimal price; // assigned elsewhere
if (price.compareTo(new BigDecimal("0.00")) == 0) {
return true;
}
What is the best way to write the if condition?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use
compareTo(BigDecimal.ZERO)instead ofequals():Comparing with the
BigDecimalconstantBigDecimal.ZEROavoids having to construct anew BigDecimal(0)every execution.FYI,
BigDecimalalso has constantsBigDecimal.ONEandBigDecimal.TENfor your convenience.Note!
The reason you can’t use
BigDecimal#equals()is that it takes scale into consideration:so it’s unsuitable for a purely numeric comparison. However,
BigDecimal.compareTo()doesn’t consider scale when comparing: