Sunday, October 28, 2018

Rounding a decimals to n number of places in Java

Why should we format numbers in applications?


In most of the applications, we may have a need to format the numbers to display them in a user friendly format. For example in accounting software, we might need to format a number as currency and limit the decimal to 2 places. In brokerage applications, we might have to display the percentage rounding the decimal part to n number of places.

The following example will demonstrate the concept of formatting numbers and rounding the decimal part to n number of places.


import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class DecimalRoundToXNumbers {

	public static void main(String[] args) {
		System.out.println(getDoubleRounded(111.15678, 2));
		System.out.println(getDoubleRounded(111.15678, 3));
		System.out.println(getDoubleRounded(111.15678, 4));
		
		System.out.println(getDoubleRoundedAsCurrency(1234.2565));
	}
	
	/**
	 * @param doubleNum
	 * @param numOfPlaces
	 * @return formattedString
	 */
	private static String getDoubleRounded(Double doubleNum, int numOfPlaces){
		
		//This is going to create a format string for the number of decimal places the user want
		String formatterString = "#."+ new String(new char[numOfPlaces]).replace("\0", "#");
		
		DecimalFormat decimalFormatter = new DecimalFormat(formatterString );
		decimalFormatter.setRoundingMode(RoundingMode.CEILING);		
		Double roundedDouble = doubleNum.doubleValue();
		return decimalFormatter.format(roundedDouble);
		
	}
	
	/**
	 * @param doubleNum
	 * @return currency formatted string
	 */
	private static String getDoubleRoundedAsCurrency(Double doubleNum){
		
		NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
		currencyFormatter.setRoundingMode(RoundingMode.CEILING);		
		Double roundedDouble = doubleNum.doubleValue();
		return currencyFormatter.format(roundedDouble);
		
	}
}

Output:
111.16
111.157
111.1568
$1,234.26

No comments:

Post a Comment