10

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 )

1
  • 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, 2018 at 21:15

4 Answers 4

15

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
  • Not right. If we do number=1; echo $(( number*80/100 )), we'll get 0
    – Lewis Chan
    Jun 27, 2021 at 2:55
  • 2
    That's because, as I mentioned, 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, 2021 at 15:04
10

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
2
1

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 .