How to use expr on float?

2019-03-14 16:50发布

I know it's really stupid question, but I don't know how to do this in bash:

20 / 30 * 100

It should be 66.67 but expr is saying 0, because it doesn't support float. What command in Linux can replace expr and do this equalation?

5条回答
狗以群分
2楼-- · 2019-03-14 17:33

bc will do this for you, but the order is important.

> echo "scale = 2; 20 * 100 / 30" | bc
66.66
> echo "scale = 2; 20 / 30 * 100" | bc
66.00

or, for your specific case:

> export ach_gs=2
> export ach_gs_max=3
> x=$(echo "scale = 2; $ach_gs * 100 / $ach_gs_max" | bc)
> echo $x
66.66

Whatever method you choose, this is ripe for inclusion as a function to make your life easier:

#!/bin/bash
function pct () {
    echo "scale = $3; $1 * 100 / $2" | bc
}

x=$(pct 2 3 2) ; echo $x # gives 66.66
x=$(pct 1 6 0) ; echo $x # gives 16
查看更多
Anthone
3楼-- · 2019-03-14 17:35

I generally use perl:

perl -e 'print 10 / 3'
查看更多
再贱就再见
4楼-- · 2019-03-14 17:45

just do it in awk

# awk 'BEGIN{print 20 / 30 * 100}'
66.6667

save it to variable

# result=$(awk 'BEGIN{print 20 / 30 * 100}')
# echo $result
66.6667
查看更多
甜甜的少女心
5楼-- · 2019-03-14 17:45
> echo "20 / 30 * 100" | bc -l
66.66666666666666666600

This is a simplification of the answer by paxdiablo. The -l sets the scale (number of digits after the decimal) to 20. It also loads a math library with trig functions and other things.

查看更多
对你真心纯属浪费
6楼-- · 2019-03-14 17:47

As reported in the bash man page:

The shell allows arithmetic expressions to be evaluated, under certain circumstances...Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error.

You can multiply by 100 earlier to get a better, partial result:

let j=20*100/30
echo $j

66

Or by a higher multiple of 10, and imagine the decimal place where it belongs:

let j=20*10000/30
echo $j

66666

查看更多
登录 后发表回答