To fix the number of digits printed for a number using printf
in Java, you can use the %
formatting codes in the format string.
Here are some examples of how to fix the number of digits printed for different types of numbers using printf
in Java:
For integers:
int num1 = 123; int num2 = 12345; System.out.printf("%03d\n", num1); // prints "123" System.out.printf("%03d\n", num2); // prints "12345"
In the above example, the %03d
formatting code specifies that the integer should be printed with at least 3 digits, padding with leading zeros if necessary.
For floating-point numbers:
double num1 = 1.23; double num2 = 123.45; System.out.printf("%.2f\n", num1); // prints "1.23" System.out.printf("%.2f\n", num2); // prints "123.45"
In the above example, the %.2f
formatting code specifies that the floating-point number should be printed with at least 2 digits after the decimal point.
You can use similar formatting codes for other types of numbers, such as long
and BigDecimal
. For more information on formatting codes and other options available with printf
, you can refer to the documentation for the Formatter
class in the Java API.