P.S.
P.S.

Reputation: 384

Why does printf() formatting not work for a decimal number all 0's?

I can't figure this one out:

gettimeofday(&time,NULL);
float stamp = ( (time.tv_sec*1000000)+(time.tv_usec) );

printf("Time Stamp = %08.3f\n",12345678.123);
printf("Time Stamp = %08.3f\n",stamp);
printf("Time Stamp = %08.3f\n",00000000.000);

Output:

Time Stamp = 12345678.123    
Time Stamp = 637973952.000    
Time Stamp = 0000.000  //?

How is it that the last printf does not print 8 0's before the decimal place (only prints 4)?

My goal is to printf a time stamp with 8 digits to the left of the decimal place and 3 to the right. (All the time, if the number is smaller, insert padded 0's).

Upvotes: 3

Views: 1972

Answers (4)

Tamer Tas
Tamer Tas

Reputation: 3298

Because you're confusing precision marker '.' with field width specifier. 0000.000 contains 8 characters. Had you asked for 10 you would've got 000000.000 (10 characters including the dot).

Also check down below for more information

A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

Upvotes: 0

Esteban E
Esteban E

Reputation: 65

if you need print 8 0's try with:

printf("Time Stamp = %012.3f\n",0.0);

Upvotes: 0

SGeorgiades
SGeorgiades

Reputation: 1821

The "8" to the left of the decimal point is NOT the number of digits to print to the left of the decimal point, but the TOTAL number of digits to print, including the decimal point itself. If you want to see 8 digits to the left of the decimal point AND 3 digits to the right (and the decimal point), you should use

printf("Time Stamp = %012.3f\n", stamp);  // 8 to the left + 1 for d.p. + 3 to the right = 12

Hope that helps!

Upvotes: 4

mvp
mvp

Reputation: 116457

printf format specifier follows this prototype:

%[flags][width][.precision][length]specifier

Width means desired total length, and precision is counted as part of it (that includes dot if present). To solve your problem, you should use format %012.3f.

Upvotes: 1

Related Questions