截断列中的小数位 [英] truncate decimal places in column
本文介绍了截断列中的小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何截断列中的小数位?我想打印第一列,第二列,将小数点后的位置(不舍入)减少到4位,然后再打印一个文本.谢谢
How to truncate decimal places in column? I want to print first comlumn, the second column, which decimal places will be cut (not round) to 4 places a then a text. Thank you
输入文件
56603.6153 2.212645
56603.6156 2.215645
56603.6158 2.210845
56603.6161 2.216175
56603.6166 2.204975
56603.6168 2.195275
56603.6171 2.219587
56603.6173 2.210778
56603.6176 2.199887
我尝试过
awk -F. '{print $1"."substr($1,5,4)" " $2"."substr($2,1,4)}' file
输出为:
56278.8 5545 2.5545
56278.8 5549 2.5549
56278.8 5554 2.5554
56278.8 5559 2.5559
56278.8 5563 2.5563
56278.8 5568 2.5568
我想得到
56278.8554 2.5545
56278.8555 2.5554
56278.8555 2.5559
56278.8556 2.5563
56278.8556 2.5568
推荐答案
您的预期输出与示例输入不匹配的事实意味着我们无法充分测试解决方案,但这也许就是您想要的:
The fact that your expected output doesn't match your sample input means we can't adequately test a solution but maybe this is what you want:
$ awk '
{ print t($1), t($2) }
function t(n, s) { s=index(n,"."); return (s ? substr(n,1,s+4) : n) }
' file
56603.6153 2.2126
56603.6156 2.2156
56603.6158 2.2108
56603.6161 2.2161
56603.6166 2.2049
56603.6168 2.1952
56603.6171 2.2195
56603.6173 2.2107
56603.6176 2.1998
如果您关心使所有值格式化而不是仅在必要时截断,则将t()的返回结果包装在 sprintf(%.04f",...)
中,例如:>
Wrap the return from t() in sprintf("%.04f",...)
if you care about making all values that format rather than just truncating when necessary, i.e.:
function t(n, s) { s=index(n,"."); return sprintf("%.04f",(s ? substr(n,1,s+4) : n)) }
这篇关于截断列中的小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文