7 ways to format double to 2 decimal places in java

Format double to 2 decimal places in java

In this post, we will see how to format double to 2 decimal places.

There are multiple ways to format double to 2 decimal places. Let’s go through them.

Using String’s format() method

You can also use String’s static method format() to print double to 2 decimal places. This method is similar to System.out.printf.
Here is an example:

💻 Awesome Tech Resources:
  • Looking for ⚒️ tech jobs? Go to our job portal.
  • Looking for tech events? Go to tech events 🗓️ Calendar.️

Output:

Double upto 2 decimal places: 2.46

Using System.out.printf

If you want to print double to 2 decimal places, this is best way to print double to 2 decimals on console.
Here is an example:

Output:

Double upto 2 decimal places: 2.46

Using Formatter

You can use java.util.Formatter‘s format() method to format double to 2 decimal places. This is similar to System.out.printf method.
Here is an example:

Output:

Double upto 2 decimal places: 2.46

Using BigDecimal

You can convert double to BigDecimal and use BigDecimal‘s setScale() method to format double to 2 decimal places You can use RoundingMode to specify rounding behavior.
Here is an example:

Output:

Double upto 2 decimal places: 2.46
Double upto 2 decimal places – RoundingMode.DOWN: 2.45
Double upto 2 decimal places – RoundingMode.UP: 2.46

Using DecimalFormat

DecimalFormat can be used by providing formatting Pattern to format double to 2 decimal places. You can use RoundingMode to specify rounding behavior.
Here is an example:

Output:

Double upto 2 decimal places: 2.46
Double upto 2 decimal places – RoundingMode.DOWN: 2.45
Double upto 2 decimal places – RoundingMode.UP: 2.46

Using NumberFormat

You can also use NumberFormat‘s setMaximumFractionDigits() to put constraint on number by decimal places and use its format() method to format double to 2 decimal places.
Here is an example:

Output:

Double d1 upto 2 decimal places: 2.01
Double d2 upto 2 decimal places: 2.98

Using Apache common library

You can use Precision‘s round() method to format double to 2 decimal places. Precision class belongs to Apache common’s common-math3 library.
Add the following dependency to pom.xml.

You can find versions of commons-math over here.
Here is an example:

Output:

Double upto 2 decimal places: 2.46

That’s all about How to format double to 2 decimal places

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.