Round a number to 2 decimal places in Java

| August 8, 2012 | 0 Comments

When we are working in a software project that uses numeric quantities and in with many different formats, such as financial applications, we have to deal with problems viewing these numbers.

For example we can use the float type to represent a given concept non-monetary concept (for monetary concepts is preferable to use BigDecimal object), such as the average of a given set of values and eventuallywe are going to display the data on screen.

The common rule is that the data type (float, double, …) are often present users with two decimals, rounding the actual accuracy that is used for calculations.

¿How to round a number to 2 decimal places in Java?

You can use two different approaches for this type of transformations: using the DecimalFormat class included in the package java.text or the NumberFormat class  within the same package. The following examples show code to implement both ways.

1. Using DecimalFormat.

1
2
DecimalFormat priceFormatter = new DecimalFormat("$#0.00"); //setting the format
result = priceFormatter.format(value); //rounded operation

The pound (#) sign simply means there can be optional digits there. The two zero’s (0) to the right of the decimal place means that it has only 2 decimal places, and will be replaced by 0s if you don’t have digits there. Te $ sign right at the start is something that I put in, because I wanted to display my prices in dollars ($).

So for example, you can also have the formatting string as “#0.00 seconds more” and it’ll show “2343.36 seconds more”.

2. Using NumberFormat.

1
2
3
4
5
NumberFormat nf = NumberFormat.getNumberInstance() ; //we get the instance of the number
nf.setGroupingUsed(false) ; // don't group by threes 
nf.setMaximumFractionDigits(2) ; //we set the max number of decimal digits.
nf.setMinimumFractionDigits(2) ; //we set the min number of decimal digits.
result = nf.format(value); //rounded operation

In this we specify the fraction number with two integers that represent the size of the number.

¿What is the difference between the two approachs?

NumberFormat.getInstance actually gets the formatter based on the locale and number style. It might actually return the DecimalFormat() object. “DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers”

If you want to specify how your numbers are formatted, then you must use the DecimalFormat constructor. If you want “the way most numbers are represented in my current locale”, then use the default instance of NumberFormat.

The complete code

This is the class that I have code for the article.

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
52
package es.mergetag.roundedDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
 
/**
* 
* Example class to demostrate how to round decimal number in java to
* two decimals in view representations.
* 
* @author Francisco Trujillo Hacha
* @version 1.0
* @date 08-07-2012
*
*/
public class RoundDecimal {
 
public static String calculateUsingNumberFormat(double value){
String result = ""; 
 
NumberFormat nf = NumberFormat.getNumberInstance() ; //we get the instance of the number
nf.setGroupingUsed(false) ; // don't group by threes 
nf.setMaximumFractionDigits(2) ; //we set the max number of decimal digits.
nf.setMinimumFractionDigits(2) ; //we set the min number of decimal digits.
result = nf.format(value); //rounded operation
 
return result;
}
 
public static String calculateUsingDecimalFormat(double value){
String result = "";
 
DecimalFormat priceFormatter = new DecimalFormat("$#0.00"); //setting the format
result = priceFormatter.format(value); //rounded operation
 
return result;
}
 
public static void main(String[] args)
 
{ 
 
double valueToRound = 3.4213284; 
 
System.out.println("Float unformatted " + valueToRound + 
" now formatted using NumberFormat " + calculateUsingNumberFormat(valueToRound));
 
System.out.println("Float unformatted " + valueToRound + 
" now formatted using DecimalFormat " + calculateUsingNumberFormat(valueToRound));
 
}
 
}

References:

Javadoc NumberFormat

JavaDoc DecimalFormat

Tags: ,

Category: Others

Leave a Reply