Different rounding with println and printf

回眸只為那壹抹淺笑 提交于 2019-12-23 07:26:37

问题


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);

回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/20141257/different-rounding-with-println-and-printf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!