Home >Java >javaTutorial >How to Format a Float to Two Decimal Places in Java?
Printing a Float with Two Decimal Places in Java: A Guide
If you're working with floating-point numbers in Java and need to display them with a specific number of decimal places, here's how to accomplish this task.
Can you use System.out.print?
No, System.out.print is not the recommended method for this purpose. Instead, you can use the printf method with a special format specifier.
How to print a float with 2 decimal places using printf:
System.out.printf("%.2f", val);
The %.2f syntax instructs Java to format the floating-point variable val with two decimal places (.2). The f represents the floating-point format.
Additional Conversion Characters:
If necessary, you can use other conversion characters:
Example:
float num = 123.456789f; System.out.printf("%.2f", num); // Output: 123.46 System.out.printf("%.0f", num); // Output: 123
Remember, these formats only affect the printed output and do not alter the underlying value of the float variable.
The above is the detailed content of How to Format a Float to Two Decimal Places in Java?. For more information, please follow other related articles on the PHP Chinese website!