The width of a double variable

  • A+

I am trying to write some text to a file using PrintWriter and I do not understand what "7" means in the next example:

double d = 12.11211; out.format(“%7.3f”, d); 

The source from where I am inspiring says that 7 means:

The 7.3 before the f denotes the width (7) and precision (3) to output d in.

The problem is that I cannot understand what that width really means. I mean, even though my variable would have more than 7 digits, it is not going to format anything.


Think of it as the total length of the string produced by the applied format.
If you take in account that there will be exactly 3 chars after the decimal point and 1 char for the decimal point itself, then it leaves 3 chars for the integer part.
Because your number has only 2 digits in the integer part the final result will be padded at the left with a white space:

double d = 12.11211; out.format(“%7.3f”, d); 

will create:

" 12.112" 


out.format(“%8.3f”, d); 

you get

"  12.112" 

and so on.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: