Prerequisites
Development environment
- JDK 1.8 Downloads
- Eclipse Mars Download
Required jar files
commons-lang-2.6.jar download
Maven dependencies
1 2 3 4 5 6 7 |
<dependencies> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> </dependencies> |
NumberUtils provides extra functionality for Java Number classes such as comparing, parsing numbers, gets maximum/minimum value from a group of numbers or an array…
Step 1 Create Java Project
Launch Eclipse IDE; Create new Java Project by going to File -> New -> Others… -> Java Project. Choose any project name you want then click Finish.
Step 2 Create Java Class
Copy the code below to clipboard; Select src folder in your project; Press CTRL + V; Eclipse IDE will automatically create package & class file with the code that’s pasted from clipboard.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package info.java.tips.util; import org.apache.commons.lang.math.NumberUtils; public class NumberUtilsDemo { public static void main(String[] args) { String sd1 = "123.4"; // Convert string to double double d1 = NumberUtils.toDouble(sd1); double d2 = 1234.5; /** * It returns -1 if the first value is less than the second. It returns * +1 if the first value is greater than the second. It returns 0 if the * values are equal. */ int result = NumberUtils.compare(d1, d2); switch (result) { case -1: System.out.println(d1 + " is less than " + d2); break; case 2: System.out.println(d1 + " is equal " + d2); break; case 3: System.out.println(d1 + " is greater than " + d2); break; } // Check numeric data String data = "123.4aaa"; if (NumberUtils.isNumber(data)) { System.out.println(data + " is a valid Java number."); } else { System.out.println(data + " is NOT a valid Java number."); } //Max & Min value double value1 = 5; double value2 = 3; double value3 = 9; System.out.println("The biggest number is " + NumberUtils.max(value1, value2, value3) + ". And smallest one is " + NumberUtils.min(value1, value2, value3)); double[] dArray = {3,6,2}; System.out.println("The biggest number is " + NumberUtils.max(dArray) + ". And smallest one is " + NumberUtils.min(dArray)); } } |
Step 3 Configure Build Path…
- Download commons-lang jar.
- Create lib folder by right click to the project select New -> Folder.
- Copy the commons-lang-2.6.jar to the lib folder.
- Right click to the project; select Build Path -> Configure Build Path… Select Libraries tab; click Add Jars… Select the jar file then click Ok.
- Click Ok to finish the configuration.
Step 5 Run the application
Right click to the class; select Run As -> Java Application.
Output
1 2 3 4 |
123.4 is less than 1234.5 123.4aaa is NOT a valid Java number. The biggest number is 9.0. And smallest one is 3.0 The biggest number is 6.0. And smallest one is 2.0 |