在BASH中,用转换字符串.在浮动 [英] In BASH convert a string with . in float

查看:82
本文介绍了在BASH中,用转换字符串.在浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a string that represent a float:

echo $NUM
5.03

我需要将此数字乘以MEGA.如果我直接这样做:

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

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

我收到一个错误:

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

推荐答案

Bash仅包含整数,没有浮点数.您需要使用类似bc的工具来正确分配result的值:

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

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

或者您可以使用awk:

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

这篇关于在BASH中,用转换字符串.在浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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