• 本页内容

92. OFMT 内置变量


OFMT 内置变量仅在 NAWK 和 GAWK 中可用。

当数字转换为字符串进行打印时,awk 使用 OFMT 格式来决定如何打印这些值。 默认值为 "%.6g",这将打印数字中包括点两边在内的总共 6 个字符。

当使用 g 时,你必须计算点两边的所有字符。 例如,"%.4g" 表示将打印 4 个字符,包括点两侧的字符。

使用 f 时,您仅计算点右侧的字符。 例如,"%.4f" 表示将在点的右侧打印 4 个字符。点左侧的字符总数在这里并不重要。

以下 「ofmt.awk」 示例显示了使用各种 OFMT 值(对于 gf)时如何打印输出。

$ cat ofmt.awk
BEGIN {
    total=143.123456789;
    print "---using g----"
    print "Default OFMT:", total;
    OFMT="%.3g";
    print "%.3g OFMT:", total;
    OFMT="%.4g";
    print "%.4g OFMT:", total;
    OFMT="%.5g";
    print "%.5g OFMT:", total;
    OFMT="%.6g";
    print "%.6g OFMT:", total;
    print "---using f----"
    OFMT="%.0f";
    print "%.0f OFMT:", total;
    OFMT="%.1f";
    print "%.1f OFMT:", total;
    OFMT="%.2f";
    print "%.2f OFMT:", total;
    OFMT="%.3f";
    print "%.3f OFMT:", total;
}

$ awk -f ofmt.awk
---using g----
Default OFMT: 143.123
%.3g OFMT: 143
%.4g OFMT: 143.1
%.5g OFMT: 143.12
%.6g OFMT: 143.123
---using f----
%.0f OFMT: 143
%.1f OFMT: 143.1
%.2f OFMT: 143.12
%.3f OFMT: 143.123