开发者

Can I initialize variable in bash using scientific notation?

开发者 https://www.devze.com 2022-12-07 19:11 出处:网络
Is it possible to initialize variable in bash using scientific notation like in python or other programming languages.

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


Using bash'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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消