Venter C.
—You don’t know how to round a value to a specific number of decimal places in Java.
There are multiple ways to round a number in Java, depending on the precision you require and how you plan to use the result.
BigDecimal
class is best suited to financial and high-precision applications.DecimalFormat
class is better suited to user-facing applications.String.format()
method is useful when formatting numbers for display purposes.BigDecimal
ClassThe Java BigDecimal
class gives you precise control over rounding while avoiding the issues caused by floating-point arithmetic. You can specify both the number of decimal places and the rounding mode.
For example, the following code creates a BigDecimal
object from the double
value and uses the setScale()
method to specify two decimal places and the HALF_UP
rounding mode:
import java.math.BigDecimal; import java.math.RoundingMode; public class Main { public static void main(String[] args) { double value = 12.34567; int decimalPlaces = 2; BigDecimal bd = new BigDecimal(Double.toString(value)); bd = bd.setScale(decimalPlaces, RoundingMode.HALF_UP); System.out.println("Rounded value: " + bd); } }
The HALF_UP
rounding mode is a common rounding strategy in which values are rounded up when the digit after the rounding place is 5
or greater.
In this case, the output will be:
Rounded value: 12.35
The precision offered by the BigDecimal
class makes this approach suitable for financial and high-precision applications.
DecimalFormat
ClassYou can use the Java DecimalFormat
class to define a format pattern that rounds numbers to a specific number of decimal places for display.
The following example creates a DecimalFormat
object with the format pattern #.##
(where #
represents digits) to round the number to 2 decimal places:
import java.text.DecimalFormat; public class Main { public static void main(String[] args) { double value = 12.34567; DecimalFormat df = new DecimalFormat("#.##"); System.out.println("Rounded value: " + df.format(value)); } }
The output will be:
Rounded value: 12.35
Because the format()
method returns the rounded number as a String
, this approach is best used to format numbers for user-facing applications. It is not ideal for calculations, as the string result is less precise than other options.
String.format()
MethodLike the DecimalFormat
class, the Java String.format()
method allows you to format a value to a specific number of decimal places and outputs it as a string.
Note the different syntax in the following example:
public class Main { public static void main(String[] args) { double value = 12.34567; String roundedValue = String.format("%.2f", value); System.out.println("Rounded value: " + roundedValue); } }
The String.format()
method is used with the format specifier %.2f
, where 2
represents the number of decimal places and f
represents a floating-point number. The result is a string with the value rounded to 2 decimal places.
The output will be:
Rounded value: 12.35
The String.format()
method is easy and useful when you need to display formatted numbers, but like DecimalFormat
, the result is a string and not suitable for further numerical calculations.
To make the rounding process reusable, you can create a custom utility method that encapsulates one of the approaches shown above.
The following example uses the BigDecimal
class:
import java.math.BigDecimal; import java.math.RoundingMode; public class Main { public static void main(String[] args) { double value = 12.34567; double roundedValue = roundToNDecimalPlaces(value, 2); System.out.println("Rounded value: " + roundedValue); } public static double roundToNDecimalPlaces(double value, int decimalPlaces) { BigDecimal bd = new BigDecimal(Double.toString(value)); bd = bd.setScale(decimalPlaces, RoundingMode.HALF_UP); return bd.doubleValue(); } }
This custom utility method creates a reusable roundToNDecimalPlaces()
method that takes the value and the number of decimal places as parameters, uses BigDecimal
to round the number, and returns the result as a double
.
BigDecimal
class documentationDecimalFormat
class documentationString.format()
method documentationRoundingMode
class documentationTasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.