how to calculate percentage from number
for example we set
number=248
and we want to know what is the 80% from $number
so how to calculate it in bash ?
expected output 198 ( exactly is 198.4 but we want to round down with floor )
how to calculate percentage from number
for example we set
number=248
and we want to know what is the 80% from $number
so how to calculate it in bash ?
expected output 198 ( exactly is 198.4 but we want to round down with floor )
bash
cannot do floating point math, but you can fake it for things like this if you don't need a lot of precision:
$ number=248
$ echo $(( number*80/100 ))
198
number=1; echo $(( number*80/100 ))
, we'll get 0
– Lewis Chan
Jun 27 '21 at 02:55
bash
cannot do floating point maths, and so 0.8 gets truncated to 0. If you want one decimal place of precision, $((1*80/10))
returns 8, which gives you the integer part of (10*number
) for you to do with what you will. These truncation errors are specifically why I included the proviso "if you don't need a lot of precision" in my answer.
– DopeGhoti
Jun 28 '21 at 15:04
Bash itself is unable to deal with floating point math.
The best bet is to use bc
like this:
$ bc <<<"248*80/100"
198
The shell (bash, sh) is able to calculate only integers:
$ bash -c 'echo $((248*80/100))'
198
The ksh93 is able to deal with floating point math:
$ ksh -c 'echo $((248*0.8))'
198.4
And with a format for 0 decimals:
$ ksh -c 'printf "%.0f\n" "$((248*0.8))"'
zsh does it differently:
$ zsh -c 'echo $((248*0.8))'
198.40000000000001
But will fall to the correct value if formatted:
$ zsh -c 'printf "%.0f\n" "$((248*0.8))"'
198
Also, awk could do it:
$ awk -vn=248 'BEGIN{print(n*0.8)}'
198.4
Or, with zero decimals:
$ awk -vn=248 'BEGIN{printf("%.0f\n",n*0.8)}'
198
With awk
expression:
$ number=248
$ awk -v n="$number" 'BEGIN{ print int(n*0.8) }'
198
Assuming p
and n
are positive, and p*n + 100
doesn't overflow the maximum integer, p
percent of n
is
rounding down:
$(( p*n / 100 ))
rounding to nearest, half rounds up:
$(( (p*n+50) / 100 ))
rounding up:
$(( (p*n+99) / 100 ))