Artificial intelligent assistant

Approximating a floating point number with correct rounding off 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.

Use `printf`:


$ printf "%.4f\
" "$A"
1.2346
$ printf "%.4f\
" "$B"
0.0000
$ printf "%.4e\
" "$B"
1.2346e-05
$ printf "%.14f\
" "$B"
0.00001234567800
$ printf "%.4g\
" "$B"
1.235e-05
$ printf "%.4g\
" "$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\
' "${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`.

xcX3v84RxoQ-4GxG32940ukFUIEgYdPy b2dbc49b368f0746daa445046a732b1c