6

How can I round all numbers in a file that countains several columns of numbers up to a certain precision? Can this be done with awk?

A single line looks like this:

text - 0.1655456615 - 0.158645 - 0.846554 - 0.85251 ##

EDIT: '-' is a column delimiter.

MaVe
  • 339
  • 4
  • 12

2 Answers2

8

It's more easily done with perl:

perl -pe 's/[-+]?\d*(?:\.?\d|\d\.)\d*(?:[eE][-+]?\d+)?/sprintf("%.2g",$&)/ge'
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • That seems to generate numbers with a different precision, e.g., 0.03747117319160571667 is rounded to 0.03747? – MaVe Nov 08 '13 at 15:01
  • 1
    That gives `0.037` for me which is a precision of 2. Maybe you want `.2f` instead of `.2g` for 2 digits after the decimal point (0.04) or `.2e` (3.75e-02) – Stéphane Chazelas Nov 08 '13 at 15:10
  • 2f was what I needed. That solved the issue, thanks! – MaVe Nov 08 '13 at 15:22
3

If you only have awk available:

awk '{
    while (match($0, /[0-9]+\.[0-9]+/)) {
        printf "%s%.2f", substr($0, 1, RSTART-1), substr($0, RSTART, RLENGTH)
        $0 = substr($0, RSTART+RLENGTH)
    }
    print
}'
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175