Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 image 377
Synetech Avatar asked Mar 31 '12 04:03

Synetech


People also ask

Can you use the precision specifier to limit the number of characters printed from a string?

I learned recently that you can control the number of characters that printf will show for a string using a precision specifier (assuming your printf implementation supports this).

How do I specify precision in printf?

You can specify a ``precision''; for example, %. 2f formats a floating-point number with two digits printed after the decimal point. You can also add certain characters which specify various options, such as how a too-narrow field is to be padded out to its field width, or what type of number you're printing.

What is the precision specifier number of significant digits?

When using %g, the precision determines the number of significant digits. The default precision is 6.


1 Answers

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); 
like image 145
Synetech Avatar answered Oct 15 '22 10:10

Synetech