【问题标题】:linux + ksh + Round down or Round up - float numberslinux + ksh + 向下舍入或向上舍入 - 浮点数
【发布时间】:2012-02-05 07:37:45
【问题描述】:

在我的 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 脚本中运行的任何其他语言

【问题讨论】:

  • 你没有给出“规则”,只是举例。他们没有回答一个明显的问题,即小数部分为 .500 时如何舍入?
  • 感谢您的评论,请参阅我的更新问题

标签: linux perl shell awk ksh


【解决方案1】:

经过简短的 google 会话后,我发现 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

【讨论】:

  • 为什么不直接将printf "%0.f\n", $_ for @list; 与 Perl 一起使用?
  • @flesk 那可能是perl -nwe 'printf "%0.f\n", $_'。直接使用printf 更短,并且一次处理一个参数,这听起来像是OP想要的。
  • @TLP:我什至没有注意到你的 Perl 单行。如果我有,我会建议你用perl -e 'printf"%0.f\n",shift' 12.49 替换它。我的意思是,当 Perl 的 printf 的行为与您的 shell 示例中的 C 等效项完全一样时,为什么要使用 Math::Round 来完成如此简单的任务?
【解决方案2】:

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

【讨论】:

  • 啊,我的错……如果是2.5,值应该是多少?
  • 您必须询问 OP。 Math::Round 似乎“朝无穷大”四舍五入,即正数向上,负数向下。
【解决方案3】:

执行非整数数学运算的 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
$

【讨论】:

    【解决方案4】:

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

    【讨论】:

    • 如何在 ksh 脚本中运行这个 perl 语法?
    • ROUNDED=$(perl -e 'print int($ARGV[0] + 0.5)' $REALVALUE) 将在脚本中完成此操作
    • 对于 bash,您可以转到 linuxconfig.org/Bash_scripting_Tutorial 并搜索“圆浮点数”并找到使用 printf 的解决方案。在 ksh 中可能类似。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多