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

前端 未结 4 1294
耶瑟儿~
耶瑟儿~ 2021-02-08 07:15

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

相关标签:
4条回答
  • 2021-02-08 07:50


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

    0 讨论(0)
  • 2021-02-08 08:03

    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.

    0 讨论(0)
  • 2021-02-08 08:08

    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.

    0 讨论(0)
  • 2021-02-08 08:12

    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.

    0 讨论(0)
提交回复
热议问题