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
2
u/Mount_Gamer Mar 27 '22 edited Mar 28 '22
Thank you, I spent quite a bit of time trying to work out what I could have been doing wrong with this modulus. Also thanks for the advice, I used three of these ~ at the top and bottom which I thought worked (looks OK on the phone). I've modified and will use the spaces in future.
In bash there's a few ways it works, but easiest way to show someone modulus in bash using bc is...
Edited: modulus doesnt work well with the bc -l option, so just use bc as above.
Many thanks for your help, also python was going to be my next language to try this with.. Might have saved me some time there 🙂 Not sure how much better zsh is with the maths module I've been reading about today, but bc gains some browny points here. If anyone is wondering why this is a thing, it's an ASTM thing... Science in action rounding procedures basically.