问题
I have this problem,
awk 'BEGIN{ x = 0.703125; p = x/2; print p }' somefile
and the output is 0.351562. But a decimal number is missing. It should be 0.3515625 So is there a way to improve the division to get all decimals stored into a variable and not only printed? So that p really holds the value 0.3515625
回答1:
It is because of the built-in value for CONVFMT (newer versions of awk) and OFMT is only 6 digit precision. You need to make it different by modifying that variable to use along with print or use printf with precision needed.
From Awk Strings and Numbers
CONVFMT'sdefault value is"%.6g", which creates a value with at most six significant digits. For some applications, you might want to change it to specify more precision. On most modern machines, 17 digits is usually enough to capture a floating-point number’s value exactly.Prior to the POSIX standard,
awkused the value ofOFMTfor converting numbers to strings.OFMTspecifies the output format to use when printing numbers with print.CONVFMTwas introduced in order to separate the semantics of conversion from the semantics of printing. BothCONVFMTandOFMThave the same default value:"%.6g". In the vast majority of cases, oldawkprograms do not change their behavior. However, these semantics forOFMTare something to keep in mind if you must port your new style program to older implementations ofawk.
awk 'BEGIN{ x = 0.703125; p = x/2; printf "%.7f", p }'
In addition to that, OP want's this high-precision number in a variable for which sprintf should be used
awk 'BEGIN{ x = 0.703125; p = x/2; pcustom=sprintf("%.7f", p) }'
or by changing the OFMT variable on GNU Awk 4.1.4,
awk 'BEGIN{ OFMT = "%0.7f"; x = 0.703125; p = x/2; print p; }'
来源:https://stackoverflow.com/questions/50020073/getting-more-decimal-positions-as-a-result-of-division-when-using-awk