help-bash
[Top][All Lists]
Advanced

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

scientific notation in Bash


From: Ante Bilandzic
Subject: scientific notation in Bash
Date: Tue, 15 Mar 2022 13:03:54 +0100

Hello,

I am aware that Bash doesn't support floating-point arithmetic - that's not
really a severe limitation, given the fact there are a lot of simple
external utilities (bc, awk, ...) which can be used for that sake, and
invoked easily in the Bash script.

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'.

Is there any way to treat the following examples equivalently in Bash:


*$ Var=44 && [[ $Var -eq 44 ]] && echo OK*
*OK*

$ Var=44e1 && [[ $Var -eq 44 ]] && echo OK
bash: [[: 44e1: value too great for base (error token is "44e1")

$ Var=44e+1 && [[ $Var -eq 44 ]] && echo OK
bash: [[: 44e: value too great for base (error token is "44e")

$ Var=44e+01 && [[ $Var -eq 44 ]] && echo OK
bash: [[: 44e: value too great for base (error token is "44e")

$ Var=4400e-2 && [[ $Var -eq 44 ]] && echo OK
bash: [[: 4400e: value too great for base (error token is "4400e")

...

And similarly when 'e' is replaced by 'E'.

Could Bash internally simply check if a string written in scientific
notation can be interpreted as an integer, and if so, just treat it that
way within the context where integers are expected: (( ... )), [[ ... -eq
... ]], etc. ?

This is relevant for the following problem: I am storing the result of
external command in a Bash variable, and I know that the result is an
integer. However, I do not have control of the default formatting of that
external command, which can differ for very large integers, for instance:

$ mawk 'BEGIN{print 8.54585e+09}'
8.54585e+09

$ gawk 'BEGIN{print 8.54585e+09}'
8545850000

The user could of course check each time if the output of external command
is written in scientific notation and transfer it to the normal notation,
but that would clearly generate a lot of overhead and trivial code on the
user's side.

Thanks!

Cheers,
Ante


reply via email to

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