Marcus McLean
Marcus McLean

Reputation: 1326

What is the difference between %0.2lf and %.2lf as printf placeholders?

I am aware that putting any number of 0's before the width of the placeholder implements zero-padding. For example, printf("%02d", 6); prints 06.

But what does putting a single 0 before the precision of the placeholder do? For example, for both printf("%0.2lf", 0.123); and printf("%.2lf", 0.123);, the output is 0.12.

If it does nothing, is there a preferred format?

Upvotes: 13

Views: 72333

Answers (4)

Aatish Sai
Aatish Sai

Reputation: 1677

Blockquote

Basically when we % w.p f for output w refers to the minimum number of position to be use for displaying the value and p refers to the number of digit after decimal point. %3.2f floating point having 3 wide and 2 number after decimal

%0.2ffloating point at least 0 wide and 2 number after decimal

%.2f floating point at least 0(default) wide and a precision of 2)

But don't misunderstand about the 0 width if you use %0.2f it can auto adjust its minimum width.

Upvotes: 1

teppic
teppic

Reputation: 8195

These examples should show the difference:

"%0.2lf", 0.123 -> 0.12 (zero padded min. width of 0, 2 decimal places).

"%6.2lf", 0.123 -> __0.12 (space padded min. width of 6, 2 decimal places).

"%06.2lf", 0.123 -> 000.12 (zero padded min. width of 6, 2 decimal places).

"%0.6lf", 0.123 -> 0.123000 (min width of 0, 6 decimal places).

The first zero specifies zero padding, followed by the minimum width, which has a default of 0. Thus it is effectively ignored by itself (since you cannot pad 0 width).


Incidentally, the correct form is %f, not %lf for printf.

Upvotes: 3

Mats Petersson
Mats Petersson

Reputation: 129344

They are "equivalent". If you were to use "%07.2", then it would make a difference, by adding extra zeros on the front.

Edit: Originally had "%04.2", which of course doesn't make any difference, because a float with two decimals is always 4 wide anyway.

Upvotes: 9

a3.14_Infinity
a3.14_Infinity

Reputation: 5843


%3.2f //(print as a floating point at least 3 wide and a precision of 2)

%0.2lf //(print as a floating point at least 0 wide and a precision of 2)

%.2lf //(print as a floating point at least 0(default) wide and a precision of 2)

Upvotes: 11

Related Questions