2

I need to make a simple floating point operation: I tried to use both BC and awk with no success...

remainingTime=$(((duration/numOfRevisions)*remainingRevision))
echo  "$(($remainingTime / 60)) minutes and $(($remainingTime % 60)) seconds remaining."

All variables are integer numbers (duration is the number of seconds) My problem is to calculate the variable remaining time, so as to use print formatted in the second line.

my attempt in Awk

remainingTime=$(awk "BEGIN {printf \"%.2f\",${duration}/${numOfRevisions}*${remainingRevision}}‌​"
Inian
  • 80,270
  • 14
  • 142
  • 161
Botacco
  • 179
  • 11
  • `bash` only supports integer arithmetic. If you want floating point, you have to do it in a language like `awk` or `bc`. – Barmar Feb 20 '17 at 10:56
  • **I tried to use both BC and awk with no success** I don't see where you try to do this. – Barmar Feb 20 '17 at 10:56
  • Can you show us your attempts with `bc` and `awk` – Inian Feb 20 '17 at 10:58
  • @Barmar, This is the awk command I tried remainingTime=$(awk "BEGIN {printf \"%.2f\",${duration}/${numOfRevisions}*${remainingRevision}}") – Botacco Feb 20 '17 at 10:59
  • You're missing the closing `)` after the `awk` command. Other than that, it works for me. – Barmar Feb 20 '17 at 11:07
  • 1
    @Inian His awk code is inside double quotes, so `bash` will expand the variables. – Barmar Feb 20 '17 at 11:08

2 Answers2

2

bash doesn't support floating point operations. With bc you need to use bc --mathlib if you want to use floating point values:

bc --mathlib <<< "(${duration}/${numberOfRevisions})*${remainingRevision}"
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • I tried to use it but I get an error, it seems the variable "remainingTime" cannot formatted anymore remainingTime=$(bc -l <<< "(${duration}/${numberOfRevisions})*${remainingRevision}") echo "$(($remainingTime / 60)) minutes and $(($remainingTime % 60)) seconds remaining." – Botacco Feb 20 '17 at 13:54
  • What do you mean? – hek2mgl Feb 20 '17 at 14:01
0

I finally solved the problem combining @Barmar solution with another solution How to calculate time difference in bash script? and https://stackoverflow.com/editing-help#comment-formatting

The resulting command is :

remainingTime=$(awk "BEGIN {printf \"%.2f\",${duration}/${revisionCounter}*${remainingRevision}}‌​")
remainingTime=${remainingTime%.*}
echo  "$(($remainingTime / 60)) minutes and $(($remainingTime % 60)) seconds remaining."
Community
  • 1
  • 1
Botacco
  • 179
  • 11