Extra leading zeros when printing float using printf?

C++CFloating PointFormattingPrintf

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshooshView Question on Stackoverflow
Solution 1 - C++AndiDogView Answer on Stackoverflow
Solution 2 - C++kennytmView Answer on Stackoverflow