Pregunta

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);
¿Fue útil?

Solución

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.

Otros consejos

This output is the due to reason of round half up operation of floating format %f. If you go through the docs, than you will get

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.

according to me, the format %f prints 1 character. the fact that it prints 0.9 is standard mathematical rounding behavior

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top