Number Manipulation On Linux

Significant Figures

The following code calculates a number to 3 significant figures.

typeset -E3 newvar=$MyVariable

Example

#Calculate to 3 Significant Figure
MyVariable=123.4567
typeset -E3 newvar=$MyVariable
echo $newvar
123

For 5 significant figures change -E3 to -E5

Example

#Calculate to 5 Significant Figure
MyVariable=123.4567
typeset -E5 newvar=$MyVariable
echo $newvar
123.46

Expanding Scientific Notation

When Calculating large numbers to significant figures, the number may be converted to scientific notation. This is not useful if used in a script. The following example shows how to expand scientific notation.

Example

#Calculate to Significant Figure
MyVariable=123456.789
typeset -E1 newvar1=$MyVariable
echo $newvar1
1e+05

#Expand Scientific Notation
newvar2=`printf "%8d\n" $newvar1`
echo $newvar2
100000
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License