Bash limiting precision of floating point variables
A simple way is to use printf
:
$ printf "%.3f\n" 0.005000000000
0.005
To remove the leading 0
, just parse it out with sed
:
$ printf "%.3f\n" 0.005000000000 | sed 's/^0//'
.005
There is a special variable called scale
. You can set this variable to limit the precision.
EXAMPLE
$ echo "300/7" | bc -l
42.85714285714285714285
To limit the precision,
$ echo "scale=2; 300/7" | bc -l
42.85
UPDATED
$ echo "scale=3; 300/7" | bc -l | sed 's/[0-9]*\././g'
.857