Reputation: 523
I have two floating-point variables, time and prev_time, and I need to subtract them, and check if less than 0. I've looked up in dozens of forums, but can't seem to find an answer that works. I need to do something similar to:
if [[ `expr $time-$prev_time | bc` -lt 0 ]]
Any help is appreciated
Upvotes: 0
Views: 1012
Reputation: 531758
From your use of [[ ... ]]
, I'll assume you are using bash
. If you only care that the difference is less than 0, you only care that $time
is less than $prev_time
. You can split the floating point values into its integer parts, then compare them separately:
IFS=. read time_int time_frac <<< $time
IFS=. read prev_in prev_frac <<< $prev_time
if (( time_int < prev_int || (time_int == prev_int && time_frac < prev_frac) )); then
Or, you can use bc
this way (plus, it's POSIX compliant):
if [ "$( echo "$time - $prev_time < 0" | bc )" = 1 ];
bc
outputs 1 if the comparison is true, 0 if false.
Upvotes: 1