Pages

Saturday, July 30, 2016

Precision specifier

The printf precision specifiers set the maximum number of characters (or minimum number of integer digits) to print. A printf precision specification always begins with a period (.) to separate it from any preceding width specifier. Like [width], precision is specified in one of two ways:
  • directly, through a decimal digit string
  • indirectly, through an asterisk (*)

If you use an "*" for the precision specifier, the next argument in the call (treated as an int) specifies the precision. If you use "*" for the width or the precision, or for both, the width argument must immediately follow the specifiers, followed by the precision argument, then the argument for the data to be converted.

.precDescription
(none) Precision set to default:
  • 1 for d, i, o, u, x, X types
  • 6 for e, E, f types
  • All significant digits for g, G types
  • Print to first null character for s types
  • No effect on c types
.0 For d, i, o, u, x types, precision set to default;
for e, E, f types, no decimal point is printed.
.n n characters or n decimal places are printed. If the output value has more than n characters, the output might be truncated or rounded. (Whether this happens depends on the type character.)
* The argument list supplies the precision specifier, which must precede the actual argument being formatted.

No numeric characters will be output for a field (i.e., the field will be blank) if the following conditions are all met:
  • you specify an explicit precision of 0
  • the format specifier for the field is one of the integer formats (d, i, o, u, or x)
  • the value to be printed is 0

How [.prec] affects conversion

Type CharEffect of [.prec] (.n) on Conversion
d i o u x X Specifies that at least n digits are printed.
  • If input argument has less than n digits, output value is left-padded with zeros.
  • If input argument has more than n digits, the output value is not truncated.
e E fSpecifies that n characters are printed after the decimal point, and the last digit printed is rounded.
g GSpecifies that at most n significant digits are printed.
cHas no effect on the output.
sSpecifies that no more than n characters are printed.

Examples
CodeOutput
printf("%.0d",0);
printf("%.0d",1);1
printf("%.0d",123);123
printf("%.0f",12.3456);12
printf("%.5d",12);00012
printf("%.1f",12.3456);12.3
printf("%.3f",12.3456);12.346
printf("%.3s","Education");Edu

No comments:

Post a Comment