Extra leading zeros when printing float using printf?

前端 未结 2 380
生来不讨喜
生来不讨喜 2020-12-03 04:23

I\'d like to be able to write a time string that looks like this: 1:04:02.1 hours using printf.
When I try to write something like this:

p         


        
相关标签:
2条回答
  • 2020-12-03 04:56

    With the %f format specifier, the "2" is treated as the minimum number of characters altogether, not the number of digits before the decimal dot. Thus you have to replace it with 4 to get two leading digits + the decimal point + one decimal digit.

    printf("%d:%02d:%04.1f hours\n", 1, 4, 2.123456);
    
    0 讨论(0)
  • 2020-12-03 05:09

    Try %04.1f instead of %02.1f. The "4" here means at least 4 characters will be printed, and "2.1" has 3 (> 2) characters, so to enable the padding zeros you need 4.

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