Getting more decimal positions as a result of division when using awk

霸气de小男生 提交于 2020-07-22 06:14:10

问题


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's default 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, awk used the value of OFMT for converting numbers to strings. OFMT specifies the output format to use when printing numbers with print. CONVFMT was introduced in order to separate the semantics of conversion from the semantics of printing. Both CONVFMT and OFMT have the same default value: "%.6g". In the vast majority of cases, old awk programs do not change their behavior. However, these semantics for OFMT are something to keep in mind if you must port your new style program to older implementations of awk.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!