1

This question already has an answer here:

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?

marked as duplicate by cuonglm, Archemar, Jenny D, garethTheRed, Braiam Oct 19 '15 at 10:38

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.

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.

  • 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 Oct 19 '15 at 8: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 8:27
  • @jimmij I'm new to shell script. Can you explain how to do with awk. That would be very helpful – Veerendra Oct 19 '15 at 8: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 8:37
  • 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

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