加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux ksh向下舍入或向上舍入 – 浮点数

发布时间:2020-12-14 01:22:12 所属栏目:Linux 来源:网络整理
导读:在我的ksh脚本中,我只需要计算整数 有时我得到浮动数字,如3.49或4.8等 所以我需要根据以下规则将浮点数转换为整数的数字(示例) 3.49 will be 32.9 will be 34.1 will be 423.51 will be 24982.4999 will be 98210.5 will be 11 ( this example if float is .
在我的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脚本中运行的任何其他语言

解决方法

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

printf "%0.fn" 4.51
5
printf "%0.fn" 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读