2

I am trying to compute the sum of the travel distance and it is computed perfectly in the text file. However, the results would be rounded off to 4 decimal places

For instance, whenever I tried to add 10.1361234 and 10.1461621 meters from Distance Log, instead of showing the original result of 20.2822855, the result will be rounded off as shown below

totaldistance.txt

2021-04-09 13:44:26 Total distance: 20.2823 meters

DistanceLog.txt

2021-04-09 12:31:55 Distance travelled: 10.1361234 meters
2021-04-09 12:31:55 Distance travelled: 10.1461621 meters

However, I wanted to keep the original decimal values without rounding off. Is there any way to do it? Attached below is my code

#!/bin/bash

SUM=0;

<DistanceLog.txt >> totaldistance.txt awk '{ SUM+=$6 } END{ print date_time,echo"Total distance:", SUM,distance }' date_time="$(date +'%F %T')" distance="meters"

Thank you!

αғsнιη
  • 35,660
Joseph
  • 35
  • Read https://unix.stackexchange.com/questions/57006/awk-high-precision-arithmetic or https://stackoverflow.com/questions/19656446/floating-point-calculations-in-awk – pLumo Apr 09 '21 at 07:10

1 Answers1

4

If you look in the awk man page, the default awk OFMT is %.6g (6 specified the number of significant digits); you can change to say .6f to specifies the number of digits after the decimal, or %f without limit. so:

<infile >>outfile awk '{ SUM+=$5 }
END{ OFMT="%.6f"; print date_time, "Total distance:", SUM, distance }' \
     date_time="$(date +'%F %T')" distance="meters"
αғsнιη
  • 35,660