我有如下要求
121.36
121.025
121.1
121.000
Run Code Online (Sandbox Code Playgroud)
期望的输出
122
122
122
121
Run Code Online (Sandbox Code Playgroud)
使用的命令
awk -F"." '{if($8>0){print $11}}'
Run Code Online (Sandbox Code Playgroud)
您要求的是ceil()(用于" 天花板 ")功能.当你正在寻找任何类型的舍入函数时,在你的例子中包含零和负数是很重要的,因为很容易弄错它所以使用这个输入文件:
$ cat file
1.999999
1.0
0.000001
0
-0.000001
-1.0
-1.999999
Run Code Online (Sandbox Code Playgroud)
我们可以测试一个ceil()函数:
$ awk 'function ceil(x, y){y=int(x); return(x>y?y+1:y)} {print $0,ceil($0)}' file
1.999999 2
1.0 1
0.000001 1
0 0
-0.000001 0
-1.0 -1
-1.999999 -1
Run Code Online (Sandbox Code Playgroud)
和相反的floor()功能:
$ awk 'function floor(x, y){y=int(x); return(x<y?y-1:y)} {print $0,floor($0)}' file
1.999999 1
1.0 1
0.000001 0
0 0
-0.000001 -1
-1.0 -1
-1.999999 -2
Run Code Online (Sandbox Code Playgroud)
上面的工作是因为int()截断为零(来自GNU awk手册):
int(x)
Return the nearest integer to x, located between x and zero and
truncated toward zero. For example, int(3) is 3, int(3.9) is 3,
int(-3.9) is -3, and int(-3) is -3 as well.
Run Code Online (Sandbox Code Playgroud)
所以int()负数已经做了你想要的天花板功能,即向上int()舍入,如果向下舍入正数,你只需要在结果中加1 .
我0.000001在样本中使用了等等,以避免人们得到假阳性测试解决方案,增加了一些数字0.9,然后加入int().
另请注意,ceil()可以缩写为:
function ceil(x){return int(x)+(x>int(x))}
Run Code Online (Sandbox Code Playgroud)
但是我为了清晰起见(如果不清楚/显而易见,结果x>int(x)为1或0)和效率(仅调用int()一次而不是两次),就按上述方式编写了它.