brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: awk int() cuts decimals off, and printf rounds half to even

Awk
~/tips/tip-awk-rounding-int-printf

echo '2.5 3.7' | awk '{print int($1), int($2), sprintf("%.0f", $1)}'

Shows how awk turns decimals into whole numbers, and why 2.5 can become 2.

Rounding in awk has two surprises. The function most people reach for doesn’t round at all, and the one that does rounds 2.5 down.

echo '2.5 3.7' | awk '{print int($1), int($2), sprintf("%.0f", $1)}'

This prints 2 3 2 in gawk, mawk and macOS awk alike. int() throws the decimals away: 3.7 becomes 3 and -3.7 becomes -3. For rounding, use printf or sprintf with %.0f. That rounds 3.7 to 4, but 2.5 to 2, because the C library rounds exact halves to the nearest even number. 3.5 goes up to 4.

For money and most reports I think that’s fine, and over many numbers it even avoids a bias. When you need the school rule, always rounding a half upward, add 0.5 and cut:

awk '{print int($1 + 0.5)}'

That works for positive numbers only; for negative ones you have to subtract 0.5 instead.

Also keep in mind that many decimals aren’t stored exactly. 0.125 is exact in binary but 2.675 isn’t, so %.2f of 2.675 gives 2.67, not 2.68. If cents must be exact, count in whole cents instead of euros.

Further reading: GNU awk manual, POSIX awk specification

More Awk tips echo 'cost: 1,50 and 2,25' | awk '{n=gsub(/,/,"."); print n": "$0}' awk -F, 'NR>1 {print > ($2".csv")}' data.csv echo 20261201 | awk '{print substr($0,1,4)"-"substr($0,5,2)"-"substr($0,7,2)}' echo 'web1:8080,5' | awk -F'[:,]' '{print $1, $2, $3}' echo /var/log/nginx/access.log | awk -F/ '{print $NF, $(NF-1)}' All Awk tips (17) All topics

Link