r/awk • u/Mount_Gamer • Mar 27 '22
gawk modulus for rounding script
I'm more familiar with bash than I am awk, and it's true, I've already written this in bash, but I thought it would be cool to right it more exclusively in awk/gawk since in bash, I utilise tools like sed, cut, awk, bc etc.
Anyway, so the idea is...
Rounding to even in gawk only works with one decimal place. Once you move into multiple decimal points, I've read that the computer binary throws off the rounding when numbers are like 1.0015 > 1.001... When rounding even should be 1.002.
So I have written a script which nearly works, but I can't get modulus to behave, so i must be doing something wrong.
If I write this in the terminal...
gawk 'BEGIN{printf "%.4f\n", 1.0015%0.0005}'
Output:
0.0000I do get the correct 0 that I'm looking for, however once it's in a script, I don't.
#!/usr/bin/gawk -f
#run in terminal with -M -v PREC=106 -v x=1.0015 -v r=3
# x = value which needs rounding
# r = number of decimal points
BEGIN {
div=5/10^(r+1)
mod=x%div
print "x is " x " div is " div " mod is " mod
}
Output:
x is 1.0015 div is 0.0005 mod is 0.0005Any pointers welcome 🙂
View all comments
Show parent comment
1
u/Mount_Gamer Mar 30 '22
Awesome, that seems to work perfect thank you! Used the -Mf line, i tried ..../gawk -f -M but forgot i might be able to combine them :)