bash expr 中的 shell 浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2362154/
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-17 21:44:09  来源:igfitidea点击:

shell float number in expr

bashshell

提问by Zenet

I'm trying to get a float number from this :

我正在尝试从中获取浮点数:

totalmark=$(expr $sum / $subjects )

Is this correct?

这样对吗?

回答by ghostdog74

bash doesn't support floats, use awk or bc/dc

bash 不支持浮点数,使用 awk 或 bc/dc

eg awk

例如 awk

totalmark=$(awk 'BEGIN{print $sum / $subjects}')

or bc

或公元前

totalmark=$(echo "scale=2;$sum/$subjects"|bc)

if you have the luxury to use different shells other than bash, try zsh or ksh

如果您有幸使用 bash 以外的不同 shell,请尝试 zsh 或 ksh

$ zsh -c 'echo $((4/1.3))'
3.0769230769230766

$ ksh -c 'echo $((4/1.3))'
3.07692307692307692

回答by Alok Singhal

I don't think bash has floating-point capabilities. You can try:

我不认为 bash 具有浮点功能。你可以试试:

echo "$sum/$subjects" | bc -l

回答by Mark Byers

Bash doesn't support floating point arithmetic. Try bcinstead.

Bash 不支持浮点运算。试试吧bc

回答by Paused until further notice.

totalmark=$(echo "scale=4;$sum/$subjects"|bc)

By the way, three answers say that Bash doesn't support floating point arithmetic. While that is true, expris an external program (/usr/bin/exprfor me) and it's the one, in particular, in this case which doesn't support floats.

顺便说一句,三个答案都说 Bash 不支持浮点运算。虽然这是真的,但它是expr一个外部程序(/usr/bin/expr对我来说),尤其是在这种情况下,它不支持浮动。