How to round a float to two decimal places in Java

How to round a float to two decimal places in Java

You can round a float to two decimal places in Java using the DecimalFormat class or by using the String.format method. Here are examples of both approaches:

Using DecimalFormat:

import java.text.DecimalFormat; public class RoundFloatExample { public static void main(String[] args) { float number = 123.456789f; // Create a DecimalFormat object with the desired format DecimalFormat df = new DecimalFormat("#.##"); // Format the float to two decimal places String rounded = df.format(number); // Convert the formatted string back to a float if needed float roundedFloat = Float.parseFloat(rounded); System.out.println("Original float: " + number); System.out.println("Rounded float: " + roundedFloat); } } 

In this example, we create a DecimalFormat object with the format "#.##", which rounds the float to two decimal places. We then format the float using df.format(number).

Using String.format:

public class RoundFloatExample { public static void main(String[] args) { float number = 123.456789f; // Use String.format to round the float to two decimal places String rounded = String.format("%.2f", number); // Convert the formatted string back to a float if needed float roundedFloat = Float.parseFloat(rounded); System.out.println("Original float: " + number); System.out.println("Rounded float: " + roundedFloat); } } 

In this example, we use String.format with the format specifier "%.2f" to round the float to two decimal places.

Both approaches will round the float to two decimal places and provide you with a formatted string. If you need the result as a float or double again, you can parse the formatted string back to a numeric type, as shown in the examples.


More Tags

angular-data firewall asp.net-roles introspection zebra-printers libsass pgrouting android-architecture gauge xpath-1.0

More Java Questions

More Housing Building Calculators

More Fitness Calculators

More Everyday Utility Calculators

More Bio laboratory Calculators