Long time i didn’t write blog post in English. I’m afraid my skill on this will slowly fade away, so here i go, switching to English 😀 .In this article i’m gonna explain about how to compare BigDecimal value in Java. For those who already have an intermediate skill in Java it’s not a big deal, but it is for newcomers. This article won’t take your precious time and won’t make you have “too long;didn’t read” feeling.
When comparing primitive data type we will definitely use comparison operator which are “<", ">” and others. Now, try using those operators to compare BigDecimal value and tell me what you got.
1 2 3 4 5 6 |
BigDecimal seven=new BigDecimal(7); BigDecimal ten=new BigDecimal(10); if(seven<ten){ } |
Yep, annoying red will show up
Short conclusion : we can’t use those operators to compare BigDecimal value.
Solution : use compareTo method
This method will return :
-1 if method caller is less then the parameter value
0 if method caller is equal then the parameter value
1 if method caller is greater then the parameter value
Here’s the snippet that might help you for better understanding
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class App{ public static void main( String[] args ){ BigDecimal seven=new BigDecimal(7); BigDecimal ten=new BigDecimal(10); if(seven.compareTo(ten)<0){ System.out.println("Return value :"+seven.compareTo(ten)); System.out.println(seven+" < "+ten); }else{ System.out.println("Noob"); } } } |
And the result
1 2 |
Return value :-1 7 < 10 |
It is self-explained i guess, isn’t it? 😀
Happy coding 🙂