如何从命令行将数字四舍五入到最接近的整数?

use*_*326 5 command-line

我有一个文件,看起来

555.92 569.472 582.389 648.078 999.702 1040.75 1386.24 1418.47 1998.26 2182.13 2384.3
Run Code Online (Sandbox Code Playgroud)

我需要像这样舍入每个数字

556 569 582 
Run Code Online (Sandbox Code Playgroud)

理想情况下,我不需要创建 tmp 文件。怎么做 ?

Ser*_*nyy 10

通过 printf 函数运行文件内容。

 $ xargs -a numbers.txt -n1 printf "%1.f "                                   
    556 569 582 648 1000 1041 1386 1418 1998 2182 2384 
Run Code Online (Sandbox Code Playgroud)

此外,Ubuntu 有一个很好的小程序numfmt,它允许将数字格式化为用户定义的标准,并且是人类可读的。

例如,

$ xargs -a numbers.txt -n1 numfmt  --to=si --round=up | xargs echo 
556 570 583 649 1.0K 1.1K 1.4K 1.5K 2.0K 2.2K 2.4K
Run Code Online (Sandbox Code Playgroud)

查看man numfmt更多信息。


cho*_*oba 5

bash只能处理整数运算。使用更强大的语言,例如 Perl:

perl -ane 'printf "%.0f ", $_ for @F' file
Run Code Online (Sandbox Code Playgroud)
  • -n 逐行读取输入
  • -a将空格上的每一行拆分为@F数组
  • %.0f 是小数点后零位的流格式


Jac*_*ijm 5

另一个 python 解决方案(一个 -liner)。在终端中运行:

python3 -c "[print(round(float(n))) for n in open('f').read().split()]"
Run Code Online (Sandbox Code Playgroud)

'f'带有浮点数的源文件在哪里,在单引号之间,例如:

python3 -c "[print(round(float(n))) for n in open('/home/jacob/Bureaublad/test').read().split()]"
Run Code Online (Sandbox Code Playgroud)

输出:

556
569
582
648
1000
1041
1386
1418
1998
2182
2384
Run Code Online (Sandbox Code Playgroud)

另一种输出方式

如果您想要一行中的数字:

python3 -c "[print(round(float(n)), end=' ') for n in open('f').read().split()]"
Run Code Online (Sandbox Code Playgroud)

(感谢@Oli!)

输出:

556 569 582 648 1000 1041 1386 1418 1998 2182 2384
Run Code Online (Sandbox Code Playgroud)

解释

命令:

python3 -c "[print(round(float(n))) for n in open('f').read().split()]"
Run Code Online (Sandbox Code Playgroud)

在部分:

open('f').read().split()
Run Code Online (Sandbox Code Playgroud)

读取文件'f',将其拆分为浮点数(现在仍为字符串)

round(float(n))
Run Code Online (Sandbox Code Playgroud)

首先将字符串 解释n为浮点数,将其四舍五入为整数

[print(round(float(n))) for n in open('f').read().split()]
Run Code Online (Sandbox Code Playgroud)

最后,生成打印命令,打印所有圆形浮点数。


hee*_*ayl 4

使用python

#!/usr/bin/env python2
with open('/path/to/file.txt') as f:
    for line in f:
        numbers = line.strip().split(' ')
        for num in numbers:
            print int(round(float(num))),
Run Code Online (Sandbox Code Playgroud)
  • 该列表将包含吐在空格 ( )numbers上的所有数字line.rstrip().split(' ')

  • 然后我们使用该round()函数对浮点数进行舍入

  • 由于输入存储为字符串,我们需要使用该float()函数将它们转换为浮点数

  • int()函数将打印丢弃小数点的数字,即仅打印整数部分

输出 :

556 569 582 648 1000 1041 1386 1418 1998 2182 2384
Run Code Online (Sandbox Code Playgroud)