I think you are missing something as using System.out.printf(), if you do not explicit formatting widths then default behavior of printf in C (which is 6 decimal places if not explicitly specified)
So if you will not specify any number to %f
then by default it will print only 1 character. However if you want to change the number after the decimal then you need to specify it like %.2f
, this will print the number to 2 decimal places.
So it is similar to writing like
System.out.printf("%f",2.00-1.10);
or
System.out.printf("%.1f",2.00-1.10);
As the general syntax for format specifier for float is:
%[flags][width][.precision][argsize]typechar
On a side note:-
Also there is a formatter class in Java for this.
An interpreter for printf-style format strings. This class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. Common Java types such as byte, BigDecimal, and Calendar are supported. Limited formatting customization for arbitrary user types is provided through the Formattable interface.
From the Oracle Docs
If the precision is not specified then the default value is 6. If the precision is less than the number of digits which would appear after the decimal point in the string returned by Float.toString(float) or Double.toString(double) respectively, then the value will be rounded using the round half up algorithm.