linux + ksh + Round down或Round up - float number

时间:2012-01-08 11:22:22

标签: linux perl shell awk ksh

在我的ksh脚本中我需要只计算整数

有时候我会得到像3.49或4.8 ......等浮动数字

所以我需要根据以下规则(例子)将浮点数转换为整数的数字

3.49     will be 3
2.9      will be 3
4.1      will be 4
23.51    will be 24
982.4999 will be 982

10.5     will be 11  ( this example if float is .5 then it will roundup )

请在ksh或awk或perl中建议如何执行此操作

可以在我的ksh脚本中运行的任何其他语言

4 个答案:

答案 0 :(得分:4)

awk中,您可以使用int()函数截断浮点数的值,使其成为整数。

[jaypal:~/Temp] cat f
3.49     will be 3
2.9      will be 3
4.1      will be 4
23.51    will be 24
982.4999 will be 982

[jaypal:~/Temp] awk '{x=int($1); print $0,x}' f
3.49     will be 3 3
2.9      will be 3 2
4.1      will be 4 4
23.51    will be 24 23
982.4999 will be 982 982

要完成,你可以做这样的事情 -

[jaypal:~/Temp] awk '{x=$1+0.5; y=int(x); print $0,y}' f
3.49     will be 3 3
2.9      will be 3 3
4.1      will be 4 4
23.51    will be 24 24
982.4999 will be 982 982

注意:我不确定您希望如何处理numbers like 2.5。上述方法将返回3 for 2.5

答案 1 :(得分:4)

在简短的谷歌会话之后,我发现printf似乎能够完成这项工作,至少在bash中找不到(找不到一个ksh的在线翻译)。

printf "%0.f\n" 4.51
5
printf "%0.f\n" 4.49
4

代码:http://ideone.com/nEFYF

注意:perl可能有点矫枉过正,就像Marius说的那样,但这是一种perl方式:

perl模块Math::Round似乎正在处理这项工作。

<强>一衬垫:

perl -MMath::Round -we 'print round $ARGV[0]' 12.49

<强>脚本:

use v5.10;
use Math::Round;
my @list = (3.49, 2.9, 4.1, 23.51, 982.4999);

say round $_ for @list;

脚本输出:

3
3
4
24
982

答案 2 :(得分:1)

执行非整数数学运算的ksh版本可能有floor(),trunc()和round()函数。无法检查所有这些,但至少在我的Mac(Lion)上,我明白了:

$ y=3.49
$ print $(( round(y) ))
3
$ y=3.51
$ print $(( round(y) ))
4
$ (( p = round(y) ))
$ print $p
4
$

答案 3 :(得分:0)

在perl中,my $i = int($f+0.5);。应该在另一个中类似,假设它们具有转换为整数或floor函数。或者,如果在javascript中,它们具有可以直接使用的Math.round函数。

相关问题