Shell – Approximating a floating point number with correct rounding off

floating pointshell-script

How can I approximate a floating point number using shell-script (say, up to 4 digits after the decimal point)? I have two examples:

A=1.2345678 and B=1.2345678E-05.

So I would like to get A=1.2346 and B=1.2346E-05.

I can do a quick job for A by using cut :

A=`echo $A | cut -c1-6`

But that gives me A=1.2345 where I was expecting the last digit round-off to be 6 (since the next digit is greater than 5). Also it does only work for one digit before the decimal point (what if I want to approximate 100.2345678 ?) Same goes for B as well.

Best Answer

Use printf:

$ printf "%.4f\n" "$A"
1.2346
$ printf "%.4f\n" "$B"
0.0000
$ printf "%.4e\n" "$B"
1.2346e-05
$ printf "%.14f\n" "$B"
0.00001234567800
$ printf "%.4g\n" "$B"
1.235e-05
$ printf "%.4g\n" "$A"
1.235

Since %e might change the exponent, to be sure of keeping it the same, you can use the shell's string manipulation features to separate the number from the exponent and print each separately:

$ B=100.12345678E-05  
$ printf '%.5fE%s\n' "${B%E*}" "${B##*E}"
100.12346E-05

The ${B%E*} prints everything up to the 1st E and ${B##*E} is everything after the first E.

Related Question