Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert exponentials and rounding numbers in BASH

Tags:

bash

awk

i have such a file

1.5000000000E-01 7.5714285714E+00 4.0000000000E-01
2.5000000000E-01 7.5714285714E+00 4.0000000000E-01

and i have to convert it to something like

0.15 7.57 0.40

i mean i want the numbers to be with only 2 decimals and not to be exponential. I want to use bash!

like image 287
ayasha Avatar asked May 22 '13 08:05

ayasha


3 Answers

Using printf with awk:

$ awk '{printf "%.2f %.2f %.2f\n",$1,$2,$3}' file
0.15 7.57 0.40
0.25 7.57 0.40

Given more fields you would want to loop like:

$ awk '{for(i=1;i<=NF;i++)printf "%.2f ",$i;print "\n"}' file
0.15 7.57 0.40
0.25 7.57 0.40
like image 169
Chris Seymour Avatar answered Oct 05 '22 12:10

Chris Seymour


This can work:

printf "%1.2f" $number

Test:

$ for i in 1.5000000000E-01 7.5714285714E+00 4.0000000000E-01 2.5000000000E-01 7.5714285714E+00 4.0000000000E-01;
do
   printf "%1.2f\n" $i
done
0.15
7.57
0.40
0.25
7.57
0.40

In your case,

cat file | xargs printf "%1.2f\n"

Test:

$ cat file | xargs printf "%1.2f\n"
0.15
7.57
0.40
0.25
7.57
0.40
like image 21
fedorqui 'SO stop harming' Avatar answered Oct 05 '22 12:10

fedorqui 'SO stop harming'


$ cat numbers.txt
1.5000000000E-01 7.5714285714E+00 4.0000000000E-01
2.5000000000E-01 7.5714285714E+00 4.0000000000E-01

$ while read F1 F2 F3;do printf "%.2f %.2f %.2f\n" $F1 $F2 $F3;done < numbers.txt
0.15 7.57 0.40
0.25 7.57 0.40
like image 23
Michał Šrajer Avatar answered Oct 05 '22 11:10

Michał Šrajer