2
time_value=$(($large / 1000))

$large could be 60 or 57. I'm expecting 57/1000=0.057. But I'm getting 0. So, is there any way to do this?

cuonglm
  • 150,973
  • 38
  • 327
  • 406
Veerendra K
  • 520
  • 2
  • 9
  • 24

1 Answers1

2

try

time_value=$((echo scale=3 ; echo $large / 1000) | bc )

where

  • scale=3 tell bc to use 3 digit after dot/comma
  • echo $large / 1000 just compute division

Please note that, once you set floating point, you have to carry it all over the place.

if $time_value above is bellow 0, it cannot be used in usual $(( )) pattern.

Archemar
  • 31,183
  • 18
  • 69
  • 104
  • Thanks, it worked!. and one more thing, it is resulting `.060`. but later in my code im doing like this `flowspersec=$((flows / time_value))` where flows could be the value 29. I'm getting error `syntax error: operand expected (error token is ".060")` – Veerendra K Oct 19 '15 at 08:21
  • 1
    @Veerendra you cannot force `bc` to add leading zero. Just use other tool like `awk` to make calculation or even shell itself if you are using e.g. `zsh`. – jimmij Oct 19 '15 at 08:27
  • @jimmij I'm new to shell script. Can you explain how to do with `awk`. That would be very helpful – Veerendra K Oct 19 '15 at 08:32
  • 1
    @Veerendra `awk '{print $1/1000}' <<<$large`. Use `printf` instead of `print` if you want to format it differently (e.g. round up). – jimmij Oct 19 '15 at 08:37
  • @jimmij `awk '{printf $1/0.060}' <<<29` that is my intention. It works fine, if I run in shell directly(`awk '{printf $1/0.060}' <<<$test` where `test=29` also works fine ). But not `awk '{printf $1/$test2}' <<<29` where `test2=0.060` – Veerendra K Oct 19 '15 at 09:55
  • 1
    @Veerendra Inside `awk` shell variable are not available, you need to pass them to `awk` with -v option: `awk -vT=$test2 '{printf $1/T}' <<<29` or `awk '{printf $1/$2}' <<<"29 $test2"` - here `$1` stores first value, and `$2` second. – jimmij Oct 19 '15 at 10:31