string 在 BASH 中将字符串转换为 . 浮动

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

In BASH convert a string with . in float

stringbashfloating-point

提问by user3472065

I have a string that represent a float:

我有一个代表浮点数的字符串:

echo $NUM
5.03

I need to multiply this number for MEGA. If I do it directly:

我需要为 MEGA 乘以这个数字。如果我直接这样做:

MEGA="1000"
result=$(($NUM*$MEGA))

I receive an error:

我收到一个错误:

syntax error: invalid arithmetic operator (error token is ".03 * 1000")

回答by chaos

Bash only has integers, no floats. You'll need a tool like bcto properly assign the value of result:

Bash 只有整数,没有浮点数。您需要一个工具bc来正确分配 的值result

result=$(bc -l <<<"${NUM}*${MEGA}")

Or you can use awk:

或者你可以使用awk

result=$(awk '{print *}' <<<"${NUM} ${MEGA}")