Learn to round off numeric values (floats and doubles) to 2 decimal places in Java. Note that we can use the given solutions to round off to any number of places according to requirements.
1. Using BigDecimal
Using BigDecimal class is the recommended approach for doing numerical operations in Java. BigDecimal is an immutable class and provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.
The BigDecimal.setScale()
method takes two arguments. The first is scale i.e. number of places to round off. The second is the rounding mode. Different rounding modes can give different results so test them out before finalizing.
The java.math.RoundingMode.HALF_EVEN is the recommended mode in most cases. This mode rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which case, round towards the even neighbor. It is sometimes known as “Banker’s rounding” and is mainly used in the USA. This mode corresponds to the IEEE 754-2019 rounding-direction attribute roundTiesToEven.
float number = 123.456f;
BigDecimal bd = new BigDecimal(number);
BigDecimal roundedOffBd = bd.setScale(2, java.math.RoundingMode.HALF_EVEN);
System.out.println(roundedOffBd); //123.46
2. Using Commons Math’s Precision class
Similar to BigDecimal, we can use the rounding mode HALF_EVEN (or any other required mode) with the Precision class provided by Apache’s commons-math3 library.
The Precision.round(scale, mode) provides a clean method that is also easy to read.
float number = 123.456f;
float roundedOffNumber = Precision.round(number, 2, RoundingMode.ROUND_HALF_EVEN.ordinal());
System.out.println(roundedOffNumber); //123.45
3. Using Math.round()
This solution does not provide the control of the rounding mode and always rounds off to mode HALF_UP. This may be useful in some situations for non-sensitive calculations where accuracy is not of that importance.
float number = 123.456f;
System.out.println(roundUp(number, 2)); //123.46
public static double roundUp(double value, int places) {
double scale = Math.pow(10, places);
return Math.round(value * scale) / scale;
}
4. Displaying The Rounded Off Value
If we only need to display the rounded-off value of a numeric number, we can use DecimalFormat
class and use its format("###.##")
method for it.
float number = 123.456f;
DecimalFormat df = new DecimalFormat("###.##");
System.out.println(df.format(number)); //123.46
5. Conclusion
This Java tutorial taught us to round off a given floating point number to 2 decimal points using different techniques. We learned to use the Decimal class (recommended), Math, Precision and DecimalFormat classes. As a best practice, always use the Decimal class with rounding mode set to HALF_EVEN.
Happy Learning !!