Thursday, December 2, 2010

Floating point mathematical operations in Shell Script

Ksh supports floating point natively but bash doesn't, bash has to rely on external command to support floating point

Bash doesn't support floating point .
[bash]$printf "%.2f\n", $((10.0/3.0))
-bash: 10.0/3.0: syntax error in expression (error token is ".0/3.0") 
Ksh supports floating point  perfectly 
[ksh]$ printf "%.2f\n", $((10.0/3.0))
3.33 
Because the input (10.0, 3.0) are floating point, the output will be floating point by default, but you can force to treat it as integer.
[ksh]$ integer x
[ksh]$ ((x=10.0/3.0))
[ksh]$printf "%.2f\n", $x
3.00 
External commands supporting  floating point
the following example shows bc and awk, which are available in any shell
$echo 'scale = 2 ;10/3' | bc
3.33 
$awk 'BEGIN {printf "%.2f\n",10/3 ;}'
3.33

No comments:

Post a Comment