I have some calculation in my script which is similar to the below example . I find that sometimes when using large decimal digits, the output gets automatically rounded off and it is affecting the program. I am not able to understand what is happening here..
awk '{
a=6.32498922
a1=6.324
b=52
c=12.65
d=(a*b/c)
d1=(a1*b/c)
printf(" d = %s;",d)
printf(" d1 = %s\n",d1)
result1=d*300
result2=d1*300
printf(" result1=> %s\n",result1)
printf(" result2=> %s\n",result2)
}' test1
prints:
d = 26; d1 = 25.9959
result1=> 7799.99
result2=> 7798.77
Where is the decimals points in "d" . And if it got rounded off, why is the decimals appearing in "result1"
Could you help me understand what really is happening ? How can i make sure that the decimals does not get rounded off automatically?
zaxxon
August 7, 2012, 6:44am
2
Use f instead of d in printf
which stands for "floating point".
1 Like
Set CONVFMT to a proper value:
awk 'BEGIN {
CONVFMT="%-20.6f"
a=6.32498922
a1=6.324
b=52
c=12.65
d=(a*b/c)
d1=(a1*b/c)
printf(" d = %s;",d)
printf(" d1 = %s\n",d1)
result1=d*300
result2=d1*300
printf(" result1=> %s\n",result1)
printf(" result2=> %s\n",result2)
}'
which gives
d = 25.999956 ; d1 = 25.995889
result1=> 7799.986706
result2=> 7798.766798
But this will give .000000 for an integer result .. That again creates issues... . For whole numbers, I do not want the "." to appear in the variable value
It will not.
awk 'BEGIN {
CONVFMT="%-20.6f"
a=19
b=20.5
printf ("a = %s\n",a)
printf ("b = %s\n",b)
}'
a = 19
b = 20.500000
Integers get converted to strings as integers, irrespective of the value of CONVFMT (or OFMT).
1 Like
i dont know.. maybe due to some other built-in vars, but i am getting it this way:
> awk 'BEGIN {
> CONVFMT="%-20.6f"
> a=30
> b=1.5
> printf ("a = %s\n",a)
> printf ("b = %s\n",b)
> c=a/b
> printf ("c = %s\n",c)
> }'
a = 30.000000
b = 1.500000
c = 20.000000