Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different rounding with println and printf

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);
like image 910
Viciouss Avatar asked Nov 22 '13 09:11

Viciouss


People also ask

Does printf round up or down?

6.1 The fprintf function. Save this answer. Show activity on this post. @RudyVelthuis: As I recall, it always rounds "1/2" up.

How do you round off in printf?

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.

Does %F round?

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.

How do I print to 2 decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.


1 Answers

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.

like image 194
Rahul Tripathi Avatar answered Sep 19 '22 23:09

Rahul Tripathi