bash 如何在浮点数上使用 expr?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1253987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:24:05  来源:igfitidea点击:

How to use expr on float?

bashfloating-pointroundingfixed-point

提问by lauriys

I know it's really stupid question, but I don't know how to do this in bash:

我知道这是一个非常愚蠢的问题,但我不知道如何在 bash 中做到这一点:

20 / 30 * 100

It should be 66.67but expr is saying 0, because it doesn't support float. What command in Linux can replace expr and do this equalation?

应该是66.67但 expr 说的是0,因为它不支持浮动。Linux 中什么命令可以代替 expr 并进行此等式?

采纳答案by Conspicuous Compiler

As reported in the bash man page:

正如 bash 手册页中所述:

The shell allows arithmetic expressions to be evaluated, under certain circumstances...Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error.
在某些情况下,shell 允许对算术表达式进行求值……尽管除以 0 被捕获并标记为错误,但在不检查溢出的固定宽度整数中进行求值。

You can multiply by 100 earlier to get a better, partial result:

您可以提前乘以 100 以获得更好的部分结果:

let j=20*100/30
echo $j

66

66

Or by a higher multiple of 10, and imagine the decimal place where it belongs:

或者乘以 10 的更高倍数,并想象它所属的小数位:

let j=20*10000/30
echo $j

66666

66666

回答by paxdiablo

bcwill do this for you, but the order is important.

bc会为你做这件事,但顺序很重要。

> echo "scale = 2; 20 * 100 / 30" | bc
66.66
> echo "scale = 2; 20 / 30 * 100" | bc
66.00

or, for your specific case:

或者,对于您的具体情况:

> export ach_gs=2
> export ach_gs_max=3
> x=$(echo "scale = 2; $ach_gs * 100 / $ach_gs_max" | bc)
> echo $x
66.66

Whatever method you choose, this is ripe for inclusion as a function to make your life easier:

无论您选择哪种方法,都可以将其包含为一个功能,让您的生活更轻松:

#!/bin/bash
function pct () {
    echo "scale = ;  * 100 / " | bc
}

x=$(pct 2 3 2) ; echo $x # gives 66.66
x=$(pct 1 6 0) ; echo $x # gives 16

回答by pgl

I generally use perl:

我一般使用perl:

perl -e 'print 10 / 3'

回答by ghostdog74

just do it in awk

只需在 awk 中进行

# awk 'BEGIN{print 20 / 30 * 100}'
66.6667

save it to variable

将其保存到变量

# result=$(awk 'BEGIN{print 20 / 30 * 100}')
# echo $result
66.6667

回答by bjc

> echo "20 / 30 * 100" | bc -l
66.66666666666666666600

This is a simplification of the answer by paxdiablo. The -l sets the scale (number of digits after the decimal) to 20. It also loads a math library with trig functions and other things.

这是paxdiablo对答案的简化。-l 将比例(小数点后的位数)设置为 20。它还加载了一个带有三角函数和其他东西的数学库。

回答by Jules G.M.

Another obvious option:

另一个明显的选择:

python -c "print(20 / 30 * 100)"

assuming you are using Python 3. Otherwise, use python3.

假设您使用的是 Python 3。否则,请使用python3.