Unix command to return maximum float value out of two after subtraction Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Unix command to return maximum float value out of two after subtraction without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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)?

Answer

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
We are here to answer your question about Unix command to return maximum float value out of two after subtraction - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji