help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: scientific notation in Bash


From: Ante Bilandzic
Subject: Re: scientific notation in Bash
Date: Tue, 15 Mar 2022 14:16:29 +0100

On Tue, Mar 15, 2022 at 1:47 PM Tapani Tarvainen <bash@tapanitarvainen.fi>
wrote:

> On Tue, Mar 15, 2022 at 08:13:28AM -0400, Greg Wooledge (greg@wooledge.org)
> wrote:
>
> > On Tue, Mar 15, 2022 at 01:03:54PM +0100, Ante Bilandzic wrote:
> > > However, there seems to be the corner case, when I was expecting that
> Bash
> > > will be able to handle the problem internally: the case when an
> integer is
> > > written in a scientific notation, using 'e' or 'E'.
> >
> > As you have already observed, bash doesn't handle that.  You would need
> > to run some external utility (e.g. awk) to convert those into a form
> > that bash can read.
> >
> > unicorn:~$ awk -v n=4.4e5 'BEGIN {printf("%d\n", n)}'
> > 440000
> > unicorn:~$ awk -v n=4.4e9 'BEGIN {printf("%d\n", n)}'
> > 4400000000
>
> Bash can do it with the printf builtin:
>
> $ printf "%.0f\n" 4.4e5
> 440000
> $ printf "%.0f\n" 4.4e9
> 4400000000
>
> So instead of Var=44e1 you could do
>
> printf -v Var "%.0f" 44e1
>

Thanks!

This works but only as a workaround, because it's clearly impractical and
inefficient to have such a conversion explicitly written for each integer
variable, whether or not it contains the integer written in sci. notation.

A priori, I do not know whether an external utility will write the large
integer in sci. notation. So I am left with:
1/ Trying to force each external utility with its own specific formatting
to return an integer in the normal notation which Bash can swallow;
2/ For each variable I expect to be an integer and whose content is
obtained from external utility, I can implement in Bash an additional
check, something like [[ $Var =~ [eE] ]], and if true, apply the conversion
via printf as you suggested. The potential danger here is that if external
utility mistakingly returns the floating-point, Bash will still see it as
an integer:

$ Var=4.1234e1
$ printf -v Var "%.0f" $Var
$ echo $Var
41

Nevermind, I can live with this, I will stick to 2/ for the time being,
unless there is a better suggestion eventually!

Thanks!

Cheers,
Ante


>
> --
> Tapani Tarvainen
>
>


reply via email to

[Prev in Thread] Current Thread [Next in Thread]