3

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.

8

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.

  • 1
    for the second one you may want to use printf "%.4e\n" to keep the exponent. – 123 Jun 26 '15 at 14:58
  • 2
    +1 or use %.4g for both and let printf apply the default rule for whether to use the e format – steeldriver Jun 26 '15 at 15:01
  • @steeldriver Nice, didn't know you could do that! – 123 Jun 26 '15 at 15:07
  • Thanks a lot. :) It works for most of the purposes. Only trouble I get when I have something like B=100.2345678E-05. Then printf "%.4g\n" "$B" yields 0.001002 and printf "%.4e\n" "$B" produces 1.0023e-03. So the exponent value changes, which I may not desire to happen. :( – hbaromega Jun 27 '15 at 13:05
  • @hbaromega what would you want to see? – terdon Jun 27 '15 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.