Operating System - HP-UX
1824971 Members
3315 Online
109678 Solutions
New Discussion юеВ

Limiting awk math output to 4 decimal places

 
SOLVED
Go to solution
Jaris Detroye
Frequent Advisor

Limiting awk math output to 4 decimal places

When I do math in AWK I get answers much more precise then I need. Is there an easy way to tell AWK to round off to 4 decimal places?

e.g. - .45678 would be .4568
4 REPLIES 4
James R. Ferguson
Acclaimed Contributor
Solution

Re: Limiting awk math output to 4 decimal places

Hi:

# echo "0.45678"|awk '{printf "%2.4f\n",$0}'

...thus, 'printf' will do it.

Regards!

...JRF...
John Poff
Honored Contributor

Re: Limiting awk math output to 4 decimal places

Hi,

You can use the printf function in awk. If you are familiar with C or Perl, it works pretty much the same way.

printf("%2.4d \n", mynum)

would format your mynum variable to two places before the decimal and four places after the decimal.

JP
Andrew Herrmann
Occasional Advisor

Re: Limiting awk math output to 4 decimal places

You could try something like:

rout = sprintf("%4.4f", odata);

I ran a quick test and get the following:

in: .45678 out: 0.4568
in: .45672 out: 0.4567

Andy
Leif Halvarsson_2
Honored Contributor

Re: Limiting awk math output to 4 decimal places

Hi,
Look at the printf
printf "%4.4f", 10/3