user2792396
user2792396

Reputation: 69

Double printf java help

May someone explain to me how printf works with double.

I tried this sample of code

double d = 12345.123456789;

System.out.printf("START%13fEND %n", d);

And the output is:

START 12345.123457END

I understand that it takes up 13 spaces the double d in this part.

But when I do the next piece of code:

System.out.printf("START%fEND %n", d);

It outputs:

START12345.123457END

Since %f is 6.2f why is it not:

START 12345.13END

Upvotes: 0

Views: 269

Answers (2)

Paul Samsotha
Paul Samsotha

Reputation: 208984

Since %f is 6.2f why is it not:

START 12345.13END

If a decimal place is not specified (%f), the default is six digits to the right of the decimal. The numbers in in front of the decimal will always be respected.

The 13 you orignally had %13f deals with the total number of character in the whole output.

START 12345.123457END

When dealing with floats, the important number you want to consider, is the number behind the decimal. %.2f%


So the main two points to remember is that the number before the . is the number of character spaces allocated, and the number after the . is the number of decimal places.

Also keep in mind though, if the number of character spaces allocated is below the number of characters, all character will still show.

Upvotes: 0

Teo
Teo

Reputation: 3213

Use this:

double d = 12345.123456789;

System.out.printf("START%.13fEND %n", d);

instead System.out.printf("START%13fEND %n", d);

Upvotes: 1

Related Questions