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

前端 未结 4 1282
耶瑟儿~
耶瑟儿~ 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 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.

提交回复
热议问题