Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra leading zeros when printing float using printf?

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?

like image 294
shoosh Avatar asked Mar 21 '10 08:03

shoosh


People also ask

How do I print float without trailing zeros?

To format floats without trailing zeros with Python, we can use the rstrip method. We interpolate x into a string and then call rstrip with 0 and '. ' to remove trailing zeroes from the number strings. Therefore, n is 3.14.

What is %A in printf?

The %a formatting specifier is new in C99. It prints the floating-point number in hexadecimal form. This is not something you would use to present numbers to users, but it's very handy for under-the-hood/technical use cases.

How do I print a printf float?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

What do you use in printf () to display a floating point value?

we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.


1 Answers

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); 
like image 50
AndiDog Avatar answered Sep 25 '22 11:09

AndiDog