Rounding Numbers in Java: How to Get n Decimal Places

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Round a Number to N Decimal Places in Java? Full Breakdown with Examples



Rounding numbers is one of those tasks every Java developer encounters, whether a beginner outputting prices to the console or an experienced engineer working with financial calculations. It seems simple enough, right? But in practice, Java rounding double hides many pitfalls: from "magical" precision errors to choosing the right tool for a specific task.



In this article, we will cover all the main ways to round a number in Java to a specified number of decimal places. You will learn when to use Math.round, why Double is dangerous in financial calculations, and why BigDecimal is your best friend when it comes to money. Let's go!



The Problem: Why Simple Rounding in Java Isn't Always Simple?



Before we move to solutions, let's understand the root of the evil. The double type in Java (as in most languages) stores floating-point numbers in binary format. Because of this, many decimal fractions (e.g., 0.1 or 0.2) cannot be represented exactly. Try executing:



System.out.println(0.1 + 0.2); // Outputs 0.30000000000000004


For screen output, this might be non-critical, but for calculations, it's a disaster. Therefore, Java rounding to 2 decimal places (or any other number) must be done consciously.



Method 1: Mathematical Rounding via Math.round



The most straightforward way is to use Math.round(). It rounds a number to the nearest integer. To get N places, we "shift" the decimal point, round, and then shift back.



Example: rounding a double to 2 decimal places:



public static double roundWithMathRound(double value, int places) {    double scale = Math.pow(10, places);    return Math.round(value * scale) / scale;}

// Usagedouble number = 3.14159265;double rounded = roundWithMathRound(number, 2);System.out.println(rounded); // 3.14


Pros: Simplicity, no dependency on external libraries.
Cons: Works with double, meaning it is still subject to precision errors at boundary values. Not suitable for finance.



Method 2: Formatting with DecimalFormat



The DecimalFormat class from the java.text package allows you not only to round but also to format a number nicely into a string. This is ideal for UI and reports.



import java.text.DecimalFormat;

public static String formatWithDecimalFormat(double value, int places) { // Create a pattern: #.00 for two places StringBuilder pattern = new StringBuilder("#."); for (int i = 0; i < places; i++) { pattern.append("0"); } DecimalFormat df = new DecimalFormat(pattern.toString()); return df.format(value);}

// UsageString result = formatWithDecimalFormat(2.71828, 3);System.out.println(result); // 2.718


You can also configure the rounding mode (RoundingMode):

df.setRoundingMode(RoundingMode.HALF_UP); // Standard mathematical rounding


Important: DecimalFormat returns a String, not a number. If you need a double for further calculations, this method is not suitable.



Method 3: BigDecimal — The Gold Standard for Precision



When precision is critical (finance, scientific calculations), BigDecimal takes the stage. It allows you to control every digit and avoid double inaccuracies.



import java.math.BigDecimal;import java.math.RoundingMode;

public static BigDecimal roundWithBigDecimal(double value, int places) {\

Blogs

Book Recommendations