Round values only when it's numerics

Hi, all

I have a field in a file looks like this(hundreds of lines):

inf
1.24101
-0.185947
-0.349179
inf
0.126597
0.240142
-0.12031

And what I expect is:

inf
1.241
-0.186
-0.349
inf
0.127
0.240
-0.120

I am trying to use awk, but I don't have much experience to figure out the problems.

cat file |awk '{if($1==[:digit:]){print $1} else if ($1== [:alpha:]){printf"%.3f\n", $1}' |head

Try using character class [:alnum:] - Alphanumeric characters:-

awk '!/[:alnum:]/{$1=sprintf("%.3f",$1)}1' file
1 Like

How about

awk '!/[^0-9-.]/ {$1 = $1+0} {print "" $1} ' CONVFMT="%.3f" file
inf
1.241
-0.186
-0.349
inf
0.127
0.240
-0.120
1 Like

Hello nengcheng,

Following awk may also help you in same.

awk '$0 !~ /[a-zA-Z]+/{printf("%.03f\n",$0);next} 1'  Input_file

Thanks,
R. Singh

1 Like

Thank you all, Yoda and RavinderSingh13' s code works for me.

---------- Post updated at 01:42 PM ---------- Previous update was at 01:32 PM ----------

Thank you, Yoda, this works great. Besides, what does the character 's' mean in this code?

1 Like

sprintf is an awk string function. For further reference check: String Functions

sprintf(format, expression1, �)
Return (without printing) the string that printf would have printed out with the same arguments

So I am using this function to format and then assign the result instead of printing.

1 Like

Great, that's an elegant solution.

A posix awk (including mawk and and some nawk) regognizes "inf" as a valid number (infinity).

awk '{printf "%.3f\n", $1}' file

GNU awk needs --posix

awk --posix '{printf "%.3f\n", $1}' file
2 Likes