Shell Float Comparison Guide with bc

In a shell script, the bc command can be used to compare floating point numbers.

#!/bin/bash

# 浮点数比较函数
function float_compare() {
    echo "$1 > $2" | bc -l
}

# 测试比较
float1=1.23
float2=3.14

result=$(float_compare $float1 $float2)
if [ $result -eq 1 ]; then
    echo "$float1 大于 $float2"
elif [ $result -eq 0 ]; then
    echo "$float1 等于 $float2"
else
    echo "$float1 小于 $float2"
fi

In the example above, the function float_compare takes two floating point numbers as parameters, passes the comparison expression to bc using the command bc -l, and returns the comparison result. Then, based on the comparison result, it uses an if statement to determine the relationship and output the result.

It is important to note that the -l option of the bc command is used to enable the math library for supporting floating point calculations.

bannerAds