awk printf 数字的宽度并将其四舍五入

Wan*_*rer 27 scripting awk printf

我需要打印出一个数字,但具有给定的宽度和四舍五入(使用 awk!)

%10s
Run Code Online (Sandbox Code Playgroud)

我有这个,但不知何故我需要连接,%d但我所做的一切,最终都会有太多的 awk 参数(因为我有更多的列)。

cuo*_*glm 36

你可以试试这个:

$ awk 'BEGIN{printf "%3.0f\n", 3.6}'
  4
Run Code Online (Sandbox Code Playgroud)

我们的格式选项有两个部分:

  • 3: 表示输出将被填充为 3 个字符。
  • .0f: 意味着输出将没有精度,意味着四舍五入。

man awk,您可以看到更多详细信息:

width   The field should be padded to this width. The field is normally padded
        with spaces. If the 0  flag  has  been  used, it is padded with zeroes.

.prec   A number that specifies the precision to use when printing.  For the %e,
        %E, %f and %F, formats, this specifies the number of digits you want
        printed to the right of the decimal point. For the %g, and %G formats,
        it specifies the maximum number of significant  digits. For the %d, %o,
        %i, %u, %x, and %X formats, it specifies the minimum number of digits to
        print. For %s, it specifies the maximum number of characters from the
        string that should be printed.
Run Code Online (Sandbox Code Playgroud)

  • 使用“%3.0f”进行舍入是舍入到最接近的偶数。不像你说的那样“四舍五入”。 (2认同)

And*_*ese 14

使用%f格式说明符,您的(浮点)数字将根据您的指定自动四舍五入。例如,要将值四舍五入为整数,请使用

$ awk 'BEGIN { printf("%.0f\n", 1.49); }'
1
$ awk 'BEGIN { printf("%.0f\n", 1.5); }'
2
Run Code Online (Sandbox Code Playgroud)

如果您想要更多的尾随数字,只需更改精度即可。


小智 5

Awk 在下面使用 sprintf 并进行无偏舍入,因此根据您的平台,如果您希望它始终舍入,您可能需要使用以下内容:

awk "BEGIN { x+=(5/2); printf('%.0f', (x == int(x)) ? x : int(x)+1) }"

没有意识到这一点可能会导致微妙但令人讨厌的错误。