在Shell脚本中计算舍入百分比而不使用"bc". [英] Calculating rounded percentage in Shell Script without using "bc"

查看:241
本文介绍了在Shell脚本中计算舍入百分比而不使用"bc".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算Shell脚本中某些项目的百分比.我想四舍五入该值,也就是说,如果结果为59.5,我应该期望60而不是59.

I'm trying to calculate percentage of certain items in Shell Script. I would like to round off the value, that is, if the result is 59.5, I should expect 60 and not 59.

item=30
total=70
percent=$((100*$item/$total))

echo $percent

这给出42.

但是实际上,结果是42.8,我会将其四舍五入为43. "bc"可以解决问题,有没有不用"bc"的方法吗?

But actually, the result is 42.8 and I would to round it off to 43. "bc" does the trick, is there a way without using "bc" ?

我无权安装任何新软件包.我的系统中不存在"dc"和"bc". 它应该是纯Shell,不能使用perl或python脚本

I'm not authorized to install any new packages. "dc" and "bc" are not present in my system. It should be purely Shell, cannot use perl or python scripts either

推荐答案

使用AWK(无bash-isms):

Use AWK (no bash-isms):

item=30
total=70
percent=$(awk "BEGIN { pc=100*${item}/${total}; i=int(pc); print (pc-i<0.5)?i:i+1 }")

echo $percent
43

这篇关于在Shell脚本中计算舍入百分比而不使用"bc".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆