0

This question already has an answer here:

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 )

marked as duplicate by Jeff Schaller, roaima, G-Man, cas, Romeo Ninov Feb 1 '18 at 10:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • I replaced the regular expression tag with numeric data; why did you tag awk and sed? Are you interested on bash command-line access to those programs to do the math, or in bash-only solutions? – Jeff Schaller Jan 31 '18 at 21:15
4

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
2

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 formated:

$ 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
0

With awk expression:

$ number=248
$ awk -v n="$number" 'BEGIN{ print int(n*0.8) }'
198
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.