指定数字的最大 printf 字段宽度(必要时截断)? [英] Specifying maximum printf field width for numbers (truncating if necessary)?

查看:82
本文介绍了指定数字的最大 printf 字段宽度(必要时截断)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用 printf 字段宽度说明符截断字符串:

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

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

> abcde

不幸的是它不适用于数字(将 d 替换为 x 是相同的):

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 特别地说这不会发生,这似乎是不必要的限制.(是的,它可以通过创建字符串等来完成,但我希望有一个 "printf 技巧" 或聪明的混搭.)

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).

使用模数!

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

这并不理想,因为它不能从左侧截断(例如,12 而不是 34),但它适用于主要用例.例如:

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);

这篇关于指定数字的最大 printf 字段宽度(必要时截断)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆