Bash + sed: trim trailing zeros from a floating point number?

I am trying to trim the final decimal numbers from a floating point number, but so far no luck.

echo "3/2" | bc -l | sed s/0\{1,\}\$//
1.50000000000000000000

I was hoping to get 1.5, but somehow the trailing zeros don't get truncated. If instead 0\{1,\}I explicitly write 0 or 000000, etc., It discards the zeros as entered, but obviously I need it to be dynamic.

What happened to 0\{1,\}?

+5
source share
7 answers
echo "3/2" | bc -l | sed '/\./ s/\.\{0,1\}0\{1,\}$//'
  • remove trailing 0 if delimited delimiter exists
  • remove the separator if there is also 0 after the separator (it is assumed that there is at least a digit before it reaches BC)
+10
source

, , scale?

$ echo "scale=1; 3/2" | bc -l 
1.5
$ echo "scale=2; 3/2" | bc -l 
1.50
$ echo "scale=5; 3/2" | bc -l 
1.50000

man bc, .

+10

$ sed:

echo "3/2" | bc -l | sed 's/0\{1,\}$//'
1.5
+6

@anubhava , awk:

$ awk 'BEGIN{print 3/2}'
1.5
+2

printf :

printf "%.1f" $(bc -l <<< '3/2')
1.5
0

grep --only-matching:

$ echo 1 + 0.1340000010202010000012301000000000 | bc -l | grep -o '.*[1-9]'
1.1340000010202010000012301

-o, --only-matching

() , .

0

Here is my take. It removes the leading zeros, and then if there is a decimal number somewhere in the number, it also removes the leading zeros. This expression also works for numbers preceded by or after spaces, if any.

sed -e "s/^\s*0*//" -e "/\./ s/0*\s*$//"
0
source

All Articles