[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Like expr, but for floating point numbers?



Krzys Majewski (majewski@cs.ubc.ca) said:
> and I take their average with "awk". This gives me some floating point
> number. Now I would like to  compare, in a shell script, this floating
> point number to some  other floating point  number. How do  people do
> this?

You could probably use awk to do it.

Anyways, here's a quick shell function that I whipped up to do simple
comparison... really, dealing with floating point in the shell is messy.
Also, this may be bash specific... I don't know if plain sh supports the $
# and % stuff.

# returns 0 if $1 > $2
# returns 1 if $1 < $2
# returns 2 if $1 = $2
# returns 3
cmp() {
	local int_a=${1%.*}
	local dec_a=${1#*.}
	local int_b=${2%.*}
	local dec_b=${2#*.}

	[ $int_a -lt $int_b ] && return 0
	[ $int_b -lt $int_a ] && return 1
	[ $int_b -eq $int_a ] && {
		[ $dec_a -lt $dec_b ] && return 0 
		[ $dec_b -lt $dec_a ] && return 1 
		[ $dec_b -eq $dec_a ] && return 2
	}
	return 3
}

I don't think the first -eq comparision is required, but it makes it a bit
more complete. It'll only work for decimals x.y where x and y are not
empty.

.adam

-- 
[                <adam@lazur.org> <laz@clustermonkey.org>                ]
[              icq #3354423 | lazur.org | clustermonkey.org              ]



Reply to: