如何在 bash shell 脚本中添加整数和浮点数

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

How to add an integer number and a float number in a bash shell script

bashshell

提问by sasuke

I have two numbers:

我有两个数字:

value1=686
value2=228.35

I am not able to add an integer and a float. Please help me out to get the result.

我无法添加整数和浮点数。请帮我得到结果。

I am running it in bash.

我在 bash 中运行它。

回答by Karoly Horvath

echo 1 + 3.5 | bc

awk "BEGIN {print 1+3.5; exit}"

python -c "print 1+3.5"

perl -e "print 1+3.5"

Just replace the numbers with your variables, eg: echo $n1 + $n2 | bc

只需用您的变量替换数字,例如: echo $n1 + $n2 | bc

回答by Konstantin Yovkov

If you have the bclanguage installed, you can do the following:

如果bc安装了该语言,则可以执行以下操作:

#!bin/bash
numone=1.234
numtwo=0.124
total=`echo $numone + $numtwo | bc`
echo $total

If you don't have bc, then you can try with awk. Just in one single line:

如果您没有bc,那么您可以尝试使用 awk。仅在一行中:

echo 1.234 2.345 | awk '{print  + }'

There are plenty of other options, also. Like python, perl, php....

还有很多其他选择。像python、perl、php....

回答by tapas dey

Bash doesn't have floating-point types, but you can use a calculator such as bc:

Bash 没有浮点类型,但您可以使用计算器,例如bc

a=686
b=228.35
c=`echo $a + $b | bc`
echo "$c"

回答by snehal

 #!/bin/Bash
echo "Enter the two numbers to be added:"
read n1
read n2
answer=$(($n1+$n2))
echo $answer