Extra leading zeros when printing float using printf?

49,862

Solution 1

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

Solution 2

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.

Share:
49,862

Related videos on Youtube

shoosh
Author by

shoosh

Working as a Software Engineer Millennium projects: https://github.com/shooshx CycleBlob, Lightcycle on a 3d surface using WebGL http://cycleblob.com

Updated on August 02, 2020

Comments

  • shoosh
    shoosh over 3 years

    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:

    printf("%d:%02d:%02.1f hours\n", 1, 4, 2.123456);
    

    I get:

    1:04:2.1 hours
    

    Is it possible to add leading zeros to a float formatting?

  • wuppi
    wuppi over 7 years
    having this for non-floats is also nice !
  • Mohammad Kholghi
    Mohammad Kholghi over 2 years
    How about negative numbers? I'd want sth like: -00.1
  • Mohammad Kholghi
    Mohammad Kholghi over 2 years
    First, turn it to positive f = fabsf(f), then -0%.1f. This works well for f<10. For f>10 -> its like -010.3. I don't want the leading 0: -10.3. Any better ideas?