The first line below will print 0.8999999999999999
because of precision loss, this is clear. But the second line will print 0.9
, I just do not understand why. Shouldn't there be the same problem with this calculation?
System.out.println(2.00-1.10);
System.out.printf("%f",2.00-1.10);
6.1 The fprintf function. Save this answer. Show activity on this post. @RudyVelthuis: As I recall, it always rounds "1/2" up.
You can use following command for rounding off. float number = 49.765; printf("%0.2f", number); You should be able to get the 2 figures after decimal point.
The %f formatter is specifically used for formatting float values (numbers with decimals). We can use the %f formatter to specify the number of decimal numbers to be returned when a floating point number is rounded up.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With