Reputation: 333
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
Input file
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
I tried this
awk -F. '{print $1"."substr($1,5,4)" " $2"."substr($2,1,4)}' file
the output was:
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
I would like to get
56278.8554 2.5545
56278.8555 2.5554
56278.8555 2.5559
56278.8556 2.5563
56278.8556 2.5568
Upvotes: 1
Views: 632
Reputation: 37404
Also, there is always the multiply-by-10000-extract-the-integer-part-divide-by-10000-and-print-4-decimals way:
$ awk '{printf "%s %0.4f\n", $1, int($2*10000)/10000}' 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
Just don't use it.
Upvotes: 1
Reputation: 203607
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
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)) }
Upvotes: 4