Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.

For example:

Use with AIround(200.3456, 2); // returns 200.35

Original version; watch out with this

Use with AIpublic static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}

This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)). Thanks to Sloin for pointing this out.

I've been using the above to round "not-too-big" doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it's best to avoid it, since more reliable ways are readily available, with cleaner code too.

So, use this instead

(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)

Use with AIpublic static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = BigDecimal.valueOf(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

Note that HALF_UP is the rounding mode "commonly taught at school". Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.

Of course, if you prefer, you can inline the above into a one-liner:
new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()

And in every case

Always remember that floating point representations using float and double are inexact. For example, consider these expressions:

Use with AI999199.1231231235 == 999199.1231231236 // true
1.03 - 0.41 // 0.6200000000000001

For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:

Use with AISystem.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));
System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));

Some excellent further reading on the topic:

  • Item 48: "Avoid float and double if exact answers are required" in Effective Java (2nd ed) by Joshua Bloch
  • What Every Programmer Should Know About Floating-Point Arithmetic

If you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.

Specifically, note that round(200, 0) returns 200.0. If you want to output "200.00", you should first round and then format the result for output (which is perfectly explained in Jesper's answer).

Answer from Jonik on Stack Overflow
Top answer
1 of 13
963

Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.

For example:

Use with AIround(200.3456, 2); // returns 200.35

Original version; watch out with this

Use with AIpublic static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}

This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)). Thanks to Sloin for pointing this out.

I've been using the above to round "not-too-big" doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it's best to avoid it, since more reliable ways are readily available, with cleaner code too.

So, use this instead

(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)

Use with AIpublic static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = BigDecimal.valueOf(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

Note that HALF_UP is the rounding mode "commonly taught at school". Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.

Of course, if you prefer, you can inline the above into a one-liner:
new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()

And in every case

Always remember that floating point representations using float and double are inexact. For example, consider these expressions:

Use with AI999199.1231231235 == 999199.1231231236 // true
1.03 - 0.41 // 0.6200000000000001

For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:

Use with AISystem.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));
System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));

Some excellent further reading on the topic:

  • Item 48: "Avoid float and double if exact answers are required" in Effective Java (2nd ed) by Joshua Bloch
  • What Every Programmer Should Know About Floating-Point Arithmetic

If you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.

Specifically, note that round(200, 0) returns 200.0. If you want to output "200.00", you should first round and then format the result for output (which is perfectly explained in Jesper's answer).

2 of 13
403

If you just want to print a double with two digits after the decimal point, use something like this:

Use with AIdouble value = 200.3456;
System.out.printf("Value: %.2f", value);

If you want to have the result in a String instead of being printed to the console, use String.format() with the same arguments:

Use with AIString result = String.format("%.2f", value);

Or use class DecimalFormat:

Use with AIDecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
🌐
Mkyong
mkyong.com › home › java › java – how to round double / float value to 2 decimal places
Java – How to round double / float value to 2 decimal places | mkyong.com
February 25, 2025 - package com.mkyong.math.rounding; import java.math.RoundingMode; import java.text.DecimalFormat; public class DecimalExample { private static final DecimalFormat df = new DecimalFormat("0.00"); public static void main(String[] args) { double input = 1205.6358; System.out.println("Original value : " + input); // Using DecimalFormat with the default RoundingMode.HALF_EVEN System.out.println("Rounded (HALF_EVEN) : " + df.format(input)); // 1205.64 // Changing to RoundingMode.DOWN df.setRoundingMode(RoundingMode.DOWN); System.out.println("Rounded (DOWN) : " + df.format(input)); // 1205.63 // Changing to RoundingMode.UP df.setRoundingMode(RoundingMode.UP); System.out.println("Rounded (UP) : " + df.format(input)); // 1205.64 } }
🌐
Baeldung
baeldung.com › home › java › java numbers › truncate a double to two decimal places in java
Truncate a Double to Two Decimal Places in Java | Baeldung
September 2, 2026 - @Test public void givenADouble_whenUsingDecimalFormat_truncateToTwoDecimalPlaces(){ DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.DOWN); double value = 1.55555555; String truncated = df.format(value); assertEquals("1.55", truncated); double negativeValue = -1.55555555; String negativeTruncated = df.format(negativeValue); assertEquals("-1.55", negativeTruncated); } Like with NumberFormat earlier, we’ve specified the use of RoundingMode.DOWN. We see again that this solution handles positive and negative numbers well, making it useful. Java’s BigDecimal class is best suited to dealing with truncating decimal places directly while keeping the result as a number we can work with.
🌐
Baeldung
baeldung.com › home › java › java numbers › how to round a number to n decimal places in java
How to Round a Number to N Decimal Places in Java | Baeldung
2 weeks ago - Double is the default type: ... However, we should never use either type for precise values like currencies. For that, and also for rounding, we can use the BigDecimal class. Let’s start with the core—Math.round()—this is typically the ...
🌐
How to do in Java
howtodoinjava.com › home › java basics › round a double to 2 decimal places in java (or n places)
Round a Double to 2 Decimal Places in Java (or N Places)
February 16, 2024 - The quickest way without BigDecimal is to multiply by 100, round to a whole number with Math.round() and divide by 100.0 again. For N places, we multiply and divide by 10 to the power of N. The division must use 100.0 and not 100, otherwise ...
🌐
Tutorialspoint
tutorialspoint.com › java › lang › math_round_double.htm
Java - Math round(double x) method
The Java Math round(double a) returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long.
🌐
Attacomsian
attacomsian.com › blog › java-round-double-float
Round a double or float number to 2 decimal places in Java
November 26, 2022 - double price = 19.5475; BigDecimal bd = new BigDecimal(Double.toString(price)); System.out.println("Price: " + bd.setScale(2, RoundingMode.HALF_EVEN)); // Price: 19.55 // RoundingMode.UP System.out.println("Price: " + bd.setScale(2, RoundingMode.UP)); // Price: 19.55 // RoundingMode.DOWN System.out.println("Price: " + bd.setScale(2, RoundingMode.DOWN)); // Price: 19.54 · The String.format() method is typically to format a string in Java.
🌐
BeginnersBook
beginnersbook.com › 2024 › 05 › how-to-round-a-number-to-two-decimal-places-in-java
How to round a number to two decimal places in Java
May 31, 2024 - import java.math.BigDecimal; import java.math.RoundingMode; public class RoundExample { public static void main(String[] args) { double doubleValue = 143.456789; float floatValue = 143.456789f; // Convert double to BigDecimal BigDecimal bdDouble = new BigDecimal(Double.toString(doubleValue)); bdDouble = bdDouble.setScale(2, RoundingMode.HALF_UP); // Convert float to BigDecimal BigDecimal bdFloat = new BigDecimal(Float.toString(floatValue)); bdFloat = bdFloat.setScale(2, RoundingMode.HALF_UP); // Output: 143.46 System.out.println("Rounded double: " + bdDouble.doubleValue()); // Output: 143.46 System.out.println("Rounded float: " + bdFloat.floatValue()); } }
Find elsewhere
🌐
John Dalesandro
johndalesandro.com › home › blog › rounding decimals in java: avoiding round-off errors with bigdecimal
Rounding Decimals in Java: Avoiding Round-Off Errors With BigDecimal
March 21, 2025 - This is the recommended method for rounding decimals in Java. BigDecimal handles large and small numbers without round-off errors, ensuring precise results. Unlike the other three methods, it operates on the original string value rather than a double, so it never inherits the roughly 15 to 17 significant-digit ceiling that limits double precision.
🌐
Onextdigital
onextdigital.com › how-to-round-doubles-in-java-to-two-decimal-places
Easy ways to round doubles in java to two decimal places
July 19, 2023 - The Apache Common library, Math.round(), BigDecimal using the setScale() method, and other tools may all round a double number to two decimal places. Commonly used by programmers “round()” method to round two decimal places to discover ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-round-a-number-to-n-decimal-places
Java Program to Round a Number to n Decimal Places - GeeksforGeeks
January 22, 2026 - import java.math.RoundingMode; import java.text.DecimalFormat; public class GFG { public static void main(String[] args) { double number = 9.97869896; DecimalFormat df = new DecimalFormat("#.####"); df.setRoundingMode(RoundingMode.FLOOR); System.out.println(df.format(number)); } }
🌐
Vultr Docs
docs.vultr.com › java › standard library › java › lang › math › round()
Java Math round() - Round Decimal Value | Vultr Docs
December 3, 2024 - The Math.round() method in Java is essential for rounding floating-point numbers to their nearest integer values. This function operates effectively across both float and double data types, ensuring accuracy whether dealing with positive or ...
🌐
Sentry
sentry.io › sentry answers › java › round a number to n decimal places in java
Java: How to Round a Number to N Decimal Places | Sentry
September 11, 2026 - 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.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Round a Double to Two Decimal Places in Java - Java Code Geeks
March 20, 2024 - When working with financial or mathematical data in Java, it’s often necessary to truncate or round floating-point numbers to a specific number of decimal places. In many cases, we might want to truncate a double to just two decimal places for display or storage purposes.
🌐
Mkyong
mkyong.com › home › java › java – display double in 2 decimal places
Java – Display double in 2 decimal places | mkyong.com
October 29, 2021 - We also can use String formater / to round the double to 2 decimal places.
🌐
Medium
medium.com › @AlexanderObregon › rounding-numbers-with-math-round-math-floor-and-math-ceil-in-java-d201bbeb85e2
Rounding Numbers with Math.round(), Math.floor(), and ...
March 7, 2025 - One limitation of Math.round() is that it always follows the .5 rule, meaning there’s no way to control whether numbers round up or down beyond that. It also behaves differently depending on the data type, returning an int for float inputs and a long for double inputs.
🌐
W3Schools
w3schools.com › java › ref_math_round.asp
Java Math round() Method
The round() method rounds a number to the nearest integer.
Top answer
1 of 16
897

Use setRoundingMode, set the RoundingMode explicitly to handle your issue with the half-even round, then use the format pattern for your required output.

Example:

DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
    Double d = n.doubleValue();
    System.out.println(df.format(d));
}

gives the output:

12
123.1235
0.23
0.1
2341234.2125

EDIT: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:

Double d = n.doubleValue() + 1e-6;

To round down, subtract the accuracy.

2 of 16
537

Assuming value is a double, you can do:

(double)Math.round(value * 100000d) / 100000d

That's for 5 digits precision. The number of zeros indicate the number of decimals.

🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Java round double value to 2 decimal places Example - Java Code Geeks
April 25, 2019 - In this step, I will create a junit test class to format a double value with 2 decimal places with Java 8 steam API. ... package org.jcg.zheng; import static org.junit.Assert.assertEquals; import java.math.RoundingMode; import java.text.NumberFormat; import java.util.stream.DoubleStream; import java.util.stream.Stream; import org.junit.Test; public class NumberFormatTest { private DoubleStream doubleStream = DoubleStream.of(-123.345, 0.4, 0.446, 124, 124.56679); @Test public void test_NumberFormat_format() { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); nf.setMi