Table of Contents
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=1And to compare these two numbers in Linux, we can type the command below.
if [[ "$NUM1" -ge "$NUM2" ]]; then echo "TRUE"; else echo "FALSE";fiEverything 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")bc command
In linux, we have a command that allows performing calculations that is bc command.
Recommended Reading: Display program’s info entry with info command
According to man page, bc is:
bc is a language that supports arbitrary precision numbers with interactive execution of statements
Notice the -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:
NUM1=0.55
NUM2=2We can see NUM2 is larger than NUM1. And if the comparison expression is [ NUM1 larger than NUM2 ], the expected result will be FALSE.
Run the command below.
if (( $(echo "$NUM1 > $NUM2" | bc -l) )); then echo "TRUE"; else echo "FALSE";fiCompare 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 NUM1 and NUM2.
We set the value as below.
NUM1=0.555
NUM2=0.444We can see, the number NUM1 is greater than NUM2. So the result we expect will be TRUE.
if (( $(echo "$NUM1 > $NUM2" | bc -l) )); then echo "TRUE"; else echo "FALSE";fi
TRUEConclusion
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.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).