bash - Awk summation is carried out without floating point precision -
i have file.txt , i'm trying summarize values of fourth , fifth columns:
^20170821^3007030^153^863.53^0.42^ ^20170821^1402675^110^581.36^0.37^ ^20170821^1404785^24^155.29^0.29^ ^20170821^1406505^40^210.51^0.00^ ^20170821^1005^1^18.00^0.00^ ^20170821^9657^7^7.28^0.00^ ^20170821^143646^86^486.59^0.08^ ^20170821^342657^3^12.60^0.00^ ^20170821^1006^4^7.04^0.04^ ^20170821^1004^1215^3502.44^12.09^ ^20170821^1007^932^6689.64^15.07^ ^20170821^378228^1^2.80^0.00^ ^20170821^704797^4^23.80^0.00^ ^20170821^705642^2^9.80^0.00^ ^20170821^703689^7^40.60^0.00^ ^20170821^148340^75^382.81^0.20^ ^20170821^257^2^5.60^0.00^ ^20170821^3702^1^2.80^0.00^ ^20170821^3703^1^7.00^0.00^ ^20170821^258^1^7.00^0.00^ ^20170821^920299^11^60.20^0.00^ ^20170821^210705^2^14.00^0.00^ ^20170821^867693^12^65.88^0.08^ ^20170821^2635085^6^33.60^0.00^ ^20170821^13211^140^409.18^0.58^ ^20170821^64^2^14.00^0.00^ ^20170821^13214^234^1685.91^1.26^ ^20170821^13212^2^34.90^0.00^ ^20170821^13213^2^2.80^0.00^ ^20170821^18385^8^7.28^0.00^ $awk -f '^' '{sum += $5} end {print sum}' file.txt i following result: 15344.2
$awk -f '^' '{sum += $6} end {print sum}' file.txt i following result: 30.48
then checked result in excel. turned out awk addition wrong in first addition. missing 0.04.
how sum column correctly?
don't leave floating point precision using print in awk, when can use printf() format-modifiers. e.g. same printf 2 digit precision control below
awk -f '^' '{sum += $5} end {printf "%0.2f",sum}' file 15344.24 from gnu awk - modifiers printf formats under section precision states,
.preca period followed integer constant specifies precision use when printing. meaning of precision varies control letter:
as side note can use print statement special awk variable ofmt specified below,
gnu awk - controlling numeric output print
the predefined variable
ofmtcontains format specificationsprintf()when wants convert number string printing. default value ofofmt"%.6g". way print prints numbers can changed supplying different format specification value ofofmt
this way example can modified define ofmt in begin clause print 2 digit precision control, i.e.
awk -f '^' 'begin{ ofmt="%.2f" }{sum += $5} end {print sum}' file 15344.24 this option available in posix compliant awk versions.
wiki

Comments
Post a Comment