Specifying maximum printf field width for numbers (truncating if necessary)?

how to print a number with a fixed character width
snprintf
sprintf
printf column width
set width in c
printf hd
format string c
printf padding

You can truncate strings with a printf field-width specifier:

printf("%.5s", "abcdefgh");

> abcde

Unfortunately it does not work for numbers (replacing d with x is the same):

printf("%2d",   1234);  // for 34
printf("%.2d",  1234);  // for 34
printf("%-2d",  1234);  // for 12
printf("%-.2d", 1234);  // for 12

> 1234

Is there an easy/trivial way to specify the number of digits to be printed even if it means truncating a number?

MSDN specifically says that it will not happen which seems unnecessarily limiting. (Yes, it can be done by creating strings and such, but I’m hoping for a "printf trick" or clever kludge.)


Like many of my best ideas, the answer came to me while lying in bed, waiting to fall asleep (there’s not much else to do at that time than think).

Use modulus!

printf("%2d\n", 1234%10);   // for 4
printf("%2d\n", 1234%100);  // for 34

printf("%2x\n", 1234%16);   // for 2
printf("%2x\n", 1234%256);  // for d2

It’s not ideal because it can’t truncate from the left (e.g., 12 instead of 34), but it works for the main use-cases. For example:

// print a decimal ruler
for (int i=0; i<36; i++)
  printf("%d", i%10);

Formatted Output and the printf function, Some functions need only one parameter, others may need many, and some do The printf function is unusual, because the number of parameters it needs is The field width you specify is the minimum number of columns that output will With string data, the precision specifier actually dictates the maximum field width. Format specification syntax: printf and wprintf functions. 10/21/2019; 16 minutes to read +4; In this article. The various printf and wprintf functions take a format string and optional arguments and produce a formatted sequence of characters for output.


If you want to truncate from the right you can convert your number to a string and then use the string field width specifier.

"%.3s".format(1234567.toString)

Format Specification Syntax: printf and wprintf Functions, The various printf and wprintf functions take a format string and Each field of the conversion specification is a character or a number that The size field specifies the size of the argument consumed and converted. be truncated when they are formatted for output unless a size prefix of ll or I64 is used. The value is not truncated when the number of digits exceeds precision. So I'd either use "%08X" or "%.8X" but "%.08X" doesn't make any sense to me. It does however seem that it doesn't make any difference, that is, all three variants seem to produce the same output.


Example from Bash command line:

localhost ~$ printf "%.3s\n" $(printf "%03d"  1234)
123
localhost ~$ 

printf(3): formatted output conversion, C99 and POSIX.1-2001 specify that the results are undefined if a call to sprintf(), If the output was truncated due to this limit then the return value is the number of an argument is required, by writing "%m$" instead of '%' and "*m$" instead of '*' In no case does a nonexistent or small field width cause truncation of a field; � printf "<%2s>", "long"; # prints "<long>" (does not truncate) If a field width obtained through * is negative, it has the same effect as the -flag: left-justification. precision, or maximum width You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a . followed by a number.


You could use snprintf to truncate from the right

char buf[10];
static const int WIDTH_INCL_NULL = 3;

snprintf(buf, WIDTH_INCL_NULL, "%d", 1234); // buf will contain 12

Data Input and Output in C, Part 2, The printf function is used to output any combination of numerical values If the number of characters exceeds the field width, additional space will be This is just the opposite of the scanf function where a maximum field width is specified. resulting in the addition of leading blanks to the truncated string. width Optional number that specifies the minimum number of characters output (see printf Width Specification). precision Optional number that specifies the maximum number of characters printed for all or part of the output field, or the minimum number of digits printed for integer values (see the How Precision Values Affect Type table).


Why not from the left? the only difference is to use simple division:

printf("%2d", 1234/100); // you get 12

printf format identifiers., By default the width of a field will be the minimum required to hold the data. If you want to main() { int number = 5; char *pointer = "little"; printf("Here is a A maximum string width can also be specified. If your type is float: use printf("%.9g", number). If your type is double: use printf("%.17g", number). Do NOT use %f, since that only specifies how many significant digits after the decimal and will truncate small numbers.


printf, fprintf, sprintf, An optional decimal digit string specifying a minimum field width. or the maximum number of character to be printed from a string in s conversion. cause truncation of a field; if the result of the conversion is wider than the field width, the field� Sometimes the minimum field width isn't known at compile-time, and must be computed at run-time. (For example, printing a table where the width of a column depends on the widest column value in the input.) In this case the field width can be specified as an asterisk ("*"), which acts like a place-holder for an int value used for the field width


C library function - fprintf(), Left-justifies within the given field width; Right justification is the default (see width sub-specifier). The value is not truncated even if the result is larger. 2. *. The width is not specified in the format string, but as an additional integer value For g and G specifiers: This is the maximum number of significant digits to be printed. A minus sign. This tells printf to left-adjust the conversion of the argument. number: An integer that specifies field width; printf will print a conversion of ARGUMENT in a field at least number characters wide. If necessary it will be padded on the left (or right, if left-adjustment is called for) to make up the field width..


16.5: Formatted Output (<TT>printf</TT> and friends), value with extra characters if necessary so that at least five characters are printed. If the output for the field ends up being larger than the specified width, however, the field essentially overflows or grows; the output is not truncated or anything. %f, and %g; or; The maximum number of characters to be printed, for %s; or� The object is formatted as a floating-point number in scientific notation. One digit appears before the decimal point, and the number of digits specified by the precision appear after the decimal point (the default is six digits, if no precision is specified). This is followed by the letter e or E, and a signed integer specifying a power of 10.