Prajwal Kumar A
Prajwal Kumar A

Reputation: 53

Can I initialize variable in bash using scientific notation?

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

Upvotes: 3

Views: 270

Answers (2)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 70882

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

Upvotes: 4

Diego Torres Milano
Diego Torres Milano

Reputation: 69328

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

Upvotes: 0

Related Questions