0

This is similar to question about getting the minimum/maximum of two numbers, but I'm interested to do the same with float numbers.

So basically I'm trying to use shell arithmetic expansion using the ternary operator, but it only works for the integers.

For example I'd like to take two numbers and subtract some number and check whether the result is above zero, if not, set it above zero.

Integers

This works great:

value=5
echo $(( $(bc <<< "$value - 10") > 0 ? $(bc <<< "$value - 10") : 1 ))

and returns 1 as expected.

Floats

However when I'm trying to convert it into float comparison, it does not work, e.g.

value=0.5
echo $(( $(bc <<< "$value - 0.8") > 0 ? $(bc <<< "$value - 0.8") : 0.1 ))

which gives the error:

-bash: -.3 > 0 ? -.3 : 0.1 : syntax error: operand expected (error token is ".3 > 0 ? -.3 : 0.1 ")

Despite bc is returning the right float number:

$ echo $(bc <<< "$value - 0.8")
-.3

I assume bash can't handle such float comparison.

Is there any simple workaround for getting min/max for the float numbers (as explained above)?

1
  • quoting the bash reference: "Evaluation is done in fixed-width integers"
    – Jeff Schaller
    Jun 28, 2016 at 15:31

1 Answer 1

1

Ok, I came up with this simple one-liner by using bc to compare the values and shell do the rest:

$ value=0.5
$ [ $(bc <<< "$value - 0.8 > 0") -eq 1 ] && echo $(bc <<< "$value - 0.8") || echo 0.1
0.1
$ [ $(bc <<< "$value - 0.2 > 0") -eq 1 ] && echo $(bc <<< "$value - 0.2") || echo 0.1
.3

Or using bc it-self, e.g.

v=0.5
bc <<< "if ($v-0.8>0) $v-0.8 else 0.1" # Result: .1
bc <<< "if ($v-0.2>0) $v-0.2 else 0.1" # Result: .3

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .