Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk printf long number padding output incorrect

Tags:

printf

awk

Arch linux 6.15.7-zen1-1-zen,

$ awk -V
GNU Awk 5.3.2, API 4.0, PMA Avon 8-g1, (GNU MPFR 4.2.2, GNU MP 6.3.0)

Start with y.csv:

4 2016201820192020
5 20162018201920202023
5 20162018201920202024
5 00000000000000002024

then, variants of printf:

$ awk '{print $1,sprintf("%020d",$2)}' y.csv
4 00002016201820192020
5 20162018201920200704
5 20162018201920200704
5 00000000000000002024
$ awk '{$2=sprintf("%020d",$2);print $1,$2}' y.csv
4 00002016201820192020
5 20162018201920200704
5 20162018201920200704
5 00000000000000002024
$ awk '{printf("%020d\n",$2)}' y.csv
00002016201820192020
20162018201920200704
20162018201920200704
00000000000000002024
$ awk '{printf("%020.0f\n",$2)}' y.csv
00002016201820192020
20162018201920200704
20162018201920200704
00000000000000002024

What's going on? The last 4 digits of the 2nd & 3rd lines are always changed, seemingly randomly, to 0704!

like image 416
joharr Avatar asked Oct 25 '25 14:10

joharr


1 Answers

What's going on?

The number is too big for an int, thus it is interpreted as a double IEEE 754.

Double can not represent all values of integer, the value is rounded to the closest representable value.

Consider reading https://www.gnu.org/software/gawk/manual/gawk.html#Other-Stuff-to-Know . Consider -M option. See https://www.binaryconvert.com/result_double.html?decimal=050048049054050048049056050048049057050048050048050048050052 .

like image 185
KamilCuk Avatar answered Oct 27 '25 06:10

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!