How can I convert milliseconds to seconds in bash, rounded to the second digit?

There is a number in milliseconds. For example, 564. You need to get the number of seconds rounded to the second digit, that is, 0.56? Use bash or packages that are the default in centos/debian. bc for example is not good. Arithmetic operations will not be performed later with the number, so it is enough to get a string in the output

 1
Author: Oleg Vilkovsky, 2019-07-30

2 answers

The team that fits the requirement:

awk '{printf "%.2f", $1 / 1000}' <<< 564

In this case, we use the awk interpreter and pass the millisecond value to it. In the construction itself, this value will be substituted for $1

To convert milliseconds to seconds, we divide the value of milliseconds by 1000, the part after the decimal point $1 / 1000, and print the resulting value using printf using the "%.2f" parameter, which outputs 2 digits after the decimal point, rounded to the nearest the whole.

In this example if we have a millisecond value of more than 1 second say 564564, then this command will return the result: 564.56

 1
Author: PotroNik, 2019-07-31 06:11:05

Using bash arithmetic operations $(( )):

n=5645
echo $(( $n/1000 )).$(( ($n % 1000)/10 ))

Conclusion:

5.64

Sequence of calculations:

  1. We select full seconds
  2. We select milliseconds from an incomplete second and leave only 2 characters
  3. We glue the obtained results into a string with the sign .

UPD: If you need to get rid of a single zero after the decimal point in the resulting result, then do it this way: res=${res%.0}

 3
Author: Jigius, 2019-08-02 06:49:58