Home > Back-end >  Can I initialize variable in bash using scientific notation?
Can I initialize variable in bash using scientific notation?

Time:12-07

Is it possible to initialize variable in bash using scientific notation like in python or other programming languages.

a=1e5

I know in bash there is no variable type while initializing. Hence the above line if printed

echo $a

produces an output like

1e5

I want the value of a to be 100000

CodePudding user response:

Using 's builtin printf [-v varname], (without any fork to bc, awk, perl or any else)!

shortly:

Strictly answering you question: Instead of

a=1e5

write:

printf -v a %.f 1e5

From scientific to number (float or integer)

printf '%.0f\n' 3e5
300000

%f is intented to produce floating numbers. %.0f mean 0 fractional digits. Note that 0 could be implicit: %.f !

printf '%.f\n' 3e5
300000

printf  '%.2f\n' 1234567890e-8
12.35

Assingning answer to/from a variable:

myvar=1.25e6
printf -v myvar %.f "$myvar"
echo $myvar
1250000

From number to scientific

printf '%.10e\n'  {749999998..750000000}
7.4999999800e 08
7.4999999900e 08
7.5000000000e 08

Assingning answer to/from a variable:

myvar=314159.26
printf -v myvar %e "$myvar"
echo $myvar
3.141593e 05

CodePudding user response:

bash does not support scientific notation or floats, in your case you can use awk

awk -v v=1e5 'BEGIN {printf("%.0f\n", v)}'

printing

100000
  •  Tags:  
  • bash
  • Related