2
answer=$(echo $(( length / 1024 )) | bc -l)

so length is a variable which has a value like 2402267538. and it needs to be divided by 1024.

executing this throws this error

")syntax error: invalid arithmetic operator (error token is " 
jlliagre
  • 29,783
  • 6
  • 61
  • 72
Animesh
  • 176
  • 1
  • 1
  • 10
  • [Your comment here](https://stackoverflow.com/questions/36216164/how-to-divide-floating-point-numbers-using-variables-with-integer-result#comment60065970_36216323) is caused by a "carriage return" character (the end of line in windows) in your text. Remove them from the variable `length` to make all work correctly. Maybe like this: `length=${length//[!-0-9]/}` –  Mar 26 '16 at 00:01

2 Answers2

0

When you do:

echo $(( length / 1024 )) | bc -l

You've already lost the part after decimal point before bc -l as $(( length / 1024 )) performs integer division.

You can use bc -l like this:

length="2402267538"
answer=$(bc -l <<<"scale=2; $length / 1024")
echo "$answer"

2345964.39

Little more verbose using awk:

answer=$(awk -v len=$length 'BEGIN{printf "%.2f\n", len/1024}')
echo "$answer"

2345964.39

Or this:

answer=$(awk -v len=$length 'BEGIN{printf "%d\n", len/1024}')
echo "$answer"

2345964
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • The first answer, throws an error like this (standard_in) 1: illegal character: ^M and the second answer retains two decimal values after the calculation – Animesh Mar 25 '16 at 09:12
  • If you don't want to restrict to 2 decimal points then use: `awk -v len=$length 'BEGIN{printf "%f\n", len/1024}'` – anubhava Mar 25 '16 at 09:20
  • Apparently, this works fine answer=$(awk -v len=$length 'BEGIN{printf "%.0f\n", len/1024}') echo $answer – Animesh Mar 25 '16 at 09:31
0

Switching to ksh would simplify the task:

$ length=2402267538

$ answer=$((length/1024.00))
$ echo $answer
2345964.392578125

One way with awk:

$ answer=$(awk "BEGIN{printf(\"%f\n\",$length/1024);}")
$ echo $answer
2345964.392578

If you only need the integer part of the result (works with both bash and ksh):

$ answer=$((length/1024))
$ echo $answer
2345964

If your length variable is a floating point number, you can trim it that way:

$ length=2402267538.12
$ ilength=${length%%.*}
$ answer=$((ilength/1024))
$ echo $answer
2345964
jlliagre
  • 29,783
  • 6
  • 61
  • 72