Home » Core Java » apache » commons » lang3 » math » NumberUtils » org.apache.commons.lang3.math.NumberUtils Example

About Arun Kumaraswamy

Arun Kumaraswamy
Arun Kumaraswamy is a Java-Oracle Developer. His technical skills span a very wide range of technologies across networks, operating systems and web servers. He specializes in programming, PL/SQL and Linux. He also conducts penetration testing for websites. In short, he is the definition of a geek. He likes watching cricket in his spare time. He has some certifications like C|EH, CDAC-DITISS, SCJP and RHCE.

org.apache.commons.lang3.math.NumberUtils Example

Hey folks, this post is about a Math Package:NumberUtils.It has few handful of utility methods. All methods are static, so you don’t have to create an instance of it.  It resides in org.apache.commons.lang3.math.NumberUtils package. You can download the jar from http://commons.apache.org/proper/commons-lang/.
 
 
 
 
 
 
 

Or using Maven

 
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

and an import is necessary import org.apache.commons.lang3.math.NumberUtils;

Here is an example on how to go about using this Library.

1. Example

NU.java

 
package com.javacodegeek;

import java.math.BigDecimal;
import org.apache.commons.lang3.Conversion;
import org.apache.commons.lang3.math.NumberUtils;

public class NU {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ConvertBigDecimal("111");
		checkWhetherNumberLegacy("111");
		checkWhetherNumberRegex("111");
		checkWhetherNumberRegex("10E-3");
		NUStyle("111");
		NUStyle("10E-3");
		NUIntMax(new int[]{1,2,5,3,77,5});
		NUIntMin(new int[]{1,2,5,3,77,5});
		
		float minusone = NumberUtils.FLOAT_MINUS_ONE;
	}
	
	public static void ConvertBigDecimal(String input) throws NumberFormatException{
		BigDecimal bd = NumberUtils.createBigDecimal(input);
		System.out.println("ConvertBigDecimal:"+input+" "+bd);
	}
	
	public static void checkWhetherNumberLegacy(String input){
		try {
	        Integer.parseInt(input);
			  System.out.println("checkWhetherNumberLegacy:"+input+" true");
			}
			catch (NumberFormatException e) {
			  System.out.println("checkWhetherNumberLegacy:"+input+" false");
			}
	}
	
	public static void checkWhetherNumberRegex(String input){
		System.out.println("checkWhetherNumberRegex:"+input
							+" "+input.matches("[-+]?\\d+(\\.\\d+)?"));
	}
	
	public static void NUStyle(String input){
		boolean res1 = NumberUtils.isNumber(input);
		System.out.println("NUStyle:"+input+" "+res1);
	}
	
	public static void NUIntMax(int[] arr){
		int max = NumberUtils.max(arr);
		System.out.println("NUIntMax: "+max);
	}
	
	public static void NUIntMin(int[] arr){
		int min = NumberUtils.min(arr);
		System.out.println("NUIntMax: "+min);
	}

}

Output

ConvertBigDecimal:111 111
checkWhetherNumberLegacy:111 true
checkWhetherNumberRegex:111 true
checkWhetherNumberRegex:10E-3 false
NUStyle:111 true
NUStyle:10E-3 true
NUIntMax: 77
NUIntMax: 1

2. Conversion

Following method will convert a String to a BigDecimal format

 
	public static void ConvertBigDecimal(String input) throws NumberFormatException{
		BigDecimal bd = NumberUtils.createBigDecimal(input);
		System.out.println("ConvertBigDecimal:"+input+" "+bd);
	}

2.1. Other Conversion methods

  • createBigDecimal(String str)  will return a BigDecimal
  • createBigInteger(String str)  will return an BigInteger
  • createDouble(String str)  will return a Double
  • createFloat(String str)  will return a Float
  • createInteger(String str)  will return a Integer on providing hex and octal notions also
  • createLong(String str)  will return a Long
  • createNumber(String str) will return a Number
  • toByte(String str)  will return a Byte, return 0 if conversion fails
  • toByte(String str, byte defaultValue)  will return Byte, if conversion fails will return default value.
  • toDouble(String str)  will return a Double, return 0 if conversion fails
  • toDouble(String str, double defaultValue)  will return a Double, if conversion fails will return default value.
  • toFloat(String str)  will return a float, return 0 if conversion fails
  • toFloat(String str, float defaultValue)  will return a float, if conversion fails will return default value
  • toInt(String str)  will return Int, return 0 if conversion fails
  • toInt(String str, int defaultValue)  will return an Int
  • toLong(String str)  will return a Long, return 0 if conversion fails
  • toLong(String str, long defaultValue) will return a Long, if conversion fails will return default value.
  • toShort(String str)  returns a Short, return 0 if conversion fails
  • toShort(String str, short defaultValue)  returns Short, default value on failed attempt to convert.

3. Finding maximum values

 
	public static void NUIntMax(int[] arr){
		int max = NumberUtils.max(arr);
		System.out.println("NUIntMax: "+max);
	}

The following methods provide a convenient way to find out maximum values in a given array.

  • max(byte[] array)
  • max(byte a, byte b, byte c)
  • max(double[] array)
  • max(double a, double b, double c)
  • max(float[] array)
  • max(float a, float b, float c)
  • max(int[] array)
  • max(int a, int b, int c)
  • max(long[] array)
  • max(long a, long b, long c)
  • max(short[] array)
  • max(short a, short b, short c)

4. Finding minimum values

 
	public static void NUIntMin(int[] arr){
		int min = NumberUtils.min(arr);
		System.out.println("NUIntMax: "+min);
	}

The following methods provide a convenient way to find out minimum values in a given array.

  • min(byte[] array)
  • min(byte a, byte b, byte c)
  • min(double[] array)
  • min(double a, double b, double c)
  • min(float[] array)
  • min(float a, float b, float c)
  • min(int[] array)
  • min(int a, int b, int c)
  • min(long[] array)
  • min(long a, long b, long c)
  • min(short[] array)
  • min(short a, short b, short c)

5. Ways to find whether a string is a Number

	
        public static void checkWhetherNumberLegacy(String input){
		try {
	        Integer.parseInt(input);
			  System.out.println("checkWhetherNumberLegacy:"+input+" true");
			}
			catch (NumberFormatException e) {
			  System.out.println("checkWhetherNumberLegacy:"+input+" false");
			}
	}

Or you can do something like…

 
	public static void checkWhetherNumberRegex(String input){
		System.out.println("checkWhetherNumberRegex:"
                +input+" "+input.matches("[-+]?\\d+(\\.\\d+)?"));
	}
}

but what about formats like “10E-3” which is a valid number format. regex will fail in that case. The solution would be more POWERFUL regex… EH… no not really. NumberUtils does have a neat solution.

	public static void NUStyle(String input){
		boolean res1 = NumberUtils.isNumber(input);
		System.out.println("NUStyle:"+input+" "+res1);
		boolean res2 = NumberUtils.isDigits(input);
		System.out.println("NUStyle:"+input+" "+res2);
	}

Returns true or false. Not having to worry about handling exceptions.

6. Some Resusable static Constants to save memory

	public static void NUStyle(String input){
		float minusonef = NumberUtils.FLOAT_MINUS_ONE;
	}
  • BYTE_MINUS_ONE
  • BYTE_ONE
  • BYTE_ZERO
  • DOUBLE_MINUS_ONE
  • DOUBLE_ONE
  • DOUBLE_ZERO
  • FLOAT_MINUS_ONE
  • FLOAT_ONE
  • FLOAT_ZERO
  • INTEGER_MINUS_ONE
  • INTEGER_ONE
  • INTEGER_ZERO
  • LONG_MINUS_ONE
  • LONG_ONE
  • LONG_ZERO
  • SHORT_MINUS_ONE
  • SHORT_ONE
  • SHORT_ZERO

Conclusion

NumberUtils is no rocket science package but has some daily utility static methods and static constants which can make your life a little bit easier, but only a little bit :).

Download
You can download the source code of this example here: NumberUtilsExample.zip
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of