|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Hi.
I am a shell script newbie and having trouble with comparing decimal numbers using Bash shell scripts. I tried below but I get syntax error: if [ $var_containing_decimal_no -lt 5 ] then ... else ... fi It seems that '-lt' operator only works with integer value. Can anyone help me ? |
|
#2
|
|||
|
|||
|
Hey! I can help you!
Shell scripting float point to int to integer floating accuracy floating arithmetic bash scripting UNIX scripting UNIX scripts bash script shell script float compare float expressions float expression shell float decimal double round float Code:
#!/bin/bash
ROUND_OFF=100000000 # This is how much accuracy we have
# (to the nearest 10 millionth for this example)
DECIMAL=3.3333333333 # This is our decimal value
COMPARE_TO=5 # This is the value we want to compare the decimal value to
#
# CONVERT OUR BIG DECIMAL INTO A BIG INTEGER FOR COMPARING
#
# bc -l does the float calculation
# awk cuts off the decimal part
int=`echo $DECIMAL '*10000000' | bc -l | awk -F '.' '{ print $1; exit; }'`
#
# IF COMPARE_TO IS DECIMAL TOO, CONVERT IT HERE JUST LIKE ABOVE
# IT'S NOT IN THIS CASE SO LEAVE THE BOTTOM COMMENT BY ITSELF FOR NOW
#
#compare_int=`echo $COMPARE_TO '*10000000' | bc -l | awk -F '.' '{ print $1; exit; }'`
compare_int=`expr $COMPARE_TO '*' $ROUND_OFF` # Since COMPARE_TO is not a float, we'll just do this than above
#
# NOW COMPARE THE NUMBERS
#
if [ $compare_int -gt $int ] ; then
echo $COMPARE_TO " > " $DECIMAL
elif [ $compare_int -lt $int ] ; then
echo $COMPARE_TO " > " $DECIMAL
else
echo $COMPARE_TO " == " $DECIMAL
fi
#
# OUTPUT:
#
#|psycho@Shiva|: ./decimal.sh
#5 > 3.3333333333
|
|
#3
|
||||
|
||||
|
man, that question was posted on March 11th, 2003 - that's over 2 years ago!!
christo
__________________
. Spiration channels: Free scripts, programming tutorials and articles Dotcut alerts: Online Press cuttings / news alerts Clearprop: UK microlight school, wiltshire Uk dating: UK safe dating with Topdates About Christo . . |
|
#4
|
|||
|
|||
|
it could be simpler
yes, bc is a very good way to do that, also LET IT SIMPLY DO the job !
this way you can compare every things: digit <> float <> hex <> oct have a look: set a to A and b to 10 Code:
#!/bin/sh
case `echo "a=$a;b=$b;r=-1;if(a==b)r=0;if(a>b)r=1;r"|bc` in
0) echo a=$a and b=$b are equal
;; 1) echo a=$a is bigger then b=$b
;; *) echo a=$a is less then b=$b
;; esac
|
![]() |
| Viewing: Dev Shed Forums > Operating Systems > UNIX Help > Comparing decimal numbers in Bash Shell |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|