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

前端 未结 5 1561
Happy的楠姐
Happy的楠姐 2021-02-19 00:09

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

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

> abcde

Unfortunately it does no

相关标签:
5条回答
  • 2021-02-19 00:12

    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
    
    0 讨论(0)
  • 2021-02-19 00:15

    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)
    
    0 讨论(0)
  • 2021-02-19 00:37

    Example from Bash command line:

    localhost ~$ printf "%.3s\n" $(printf "%03d"  1234)
    123
    localhost ~$ 
    
    0 讨论(0)
  • 2021-02-19 00:37

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

    printf("%2d", 1234/100); // you get 12
    
    0 讨论(0)
  • 2021-02-19 00:39

    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);
    
    0 讨论(0)
提交回复
热议问题