7 ways to print float to 2 decimal places in java

Print float to 2 decimal places in java

In this post, we will see how to print float to 2 decimal places in java.
There are multiple ways to how to print float to 2 decimal places in java.

1. Using System.out.printf

In case, if you just want to print float to 2 decimal places, this is best method. You can simply use System.out.printf with format %.2f.
Here is an example:

Output:

Float upto 2 decimal places: 1.23

2. Using String’s format() method

String class also provide static method format() which you can use to print float to 2 decimal places in java. This works similar to System.out.printf.
Here is an example:

Output:

Float upto 2 decimal places: 1.23

3. Using Formatter

java.util.Formatter class provides format() method which you can use to print float to 2 decimal places in java. This works similar to System.out.printf
Here is an example:

Output:

Float upto 2 decimal places: 1.23

4. Using NumberFormat

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

Output:

Float f1 upto 2 decimal places: 1.01
Float f2 upto 2 decimal places: 1.87

5. Using BigDecimal

You can convert float to BigDecimal and use BigDecimal‘s setScale() method to print float to 2 decimal places.
Here is an example:

Output:

Float upto 2 decimal places: 1.23
Float upto 2 decimal places – RoundingMode.DOWN: 1.23
Float upto 2 decimal places – RoundingMode.UP: 1.24

6. Using DecimalFormat

You can provide formatting pattern to DecimalFormat class to print float to 2 decimal places. Here, RoundingMode can be used to control rounding behavior.
Here is an example:

Output:

Float upto 2 decimal places: 1.23
Float upto 2 decimal places using RoundingMode.DOWN: 1.23
Float upto 2 decimal places using RoundingMode.UP: 1.24

7. Using Apache common library

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

You can change 3.6.1 to latest version if you want from here.
Here is an example:

Output:

Print float upto 2 decimal places: 1.23

That’s all about How to print float to 2 decimal places

Was this post helpful?

Leave a Reply

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