WriteBash - This article will show you how to compare floating point number in bash.
Here are my shared experiences while working with the Linux system.
Compare 2 common numbers
Usually, we compare two integer numbers. For example, we have 2 numbers as follows:
$ NUM1=2 $ NUM2=1
And to compare these two numbers in Linux, we can type the command below.
$ if [[ "$NUM1" -ge "$NUM2" ]]; then echo "TRUE"; else echo "FALSE";fi
Everything seems to be fine until now. But if we change
NUM1=0.5 for example. You will get an error below.
bash: [[: 0.5: syntax error: invalid arithmetic operator (error token is ".5")
In linux, we have a command that allows performing calculations that is
Recommended Reading: Display program’s info entry with info command
According to man page,
bc is a language that supports arbitrary precision numbers with interactive execution of statements
-l option of the
bc command, which is equivalent to
--mathlib, which will load the standard math library.
Compare floating point number
Basically, we will have two cases to compare as follows.
Floating point number with integer number
Recommended Reading: Calculate percent of memory used in Linux
For example, we have 2 numbers as follows:
linuxmint ~ # NUM1=0.55 linuxmint ~ # NUM2=2
We can see
NUM2 is larger than
NUM1. And if the comparison expression is
[ NUM1 larger than NUM2 ], the expected result will be
Run the command below.
linuxmint ~ # if (( $(echo "$NUM1 > $NUM2" | bc -l) )); then echo "TRUE"; else echo "FALSE";fi
Compare two floating point numbers
Now, we will compare floating point number with other floating point number.
With the same comparison command above, we will now change the value for two numbers
We set the value as below.
linuxmint ~ # NUM1=0.555 linuxmint ~ # NUM2=0.444
We can see, the number
NUM1 is greater than
NUM2. So the result we expect will be
linuxmint ~ # if (( $(echo "$NUM1 > $NUM2" | bc -l) )); then echo "TRUE"; else echo "FALSE";fi TRUE
I have written scripts for various purposes. And in those times, many times I have encountered the need to compare two values that are two floating-point numbers.
Without the bc command and not knowing how to use it, this will become very difficult. Hope this small article makes it easier for you to work.If you liked this article, then please subscribe to our YouTube Channel for more video tutorials. You can also find us on Twitter and Facebook.
If you appreciate what we share in this blog, you can support us by:
- Stay connected to: Facebook | Twitter | Google Plus | YouTube
- Subscribe email to recieve new posts from us: Sign up now.
- Start your own blog with SSD VPS - Free Let's Encrypt SSL ($2.5/month).
- Become a Supporter - Make a contribution via PayPal.
- Support us by purchasing Ribbon Lite Child theme being using on this website.
We are thankful for your support.