RocketNuts
RocketNuts

Reputation: 11130

bash + sed: trim trailing zeroes off a floating point number?

I'm trying to get trim off trailing decimal zeroes off a floating point number, but no luck so far.

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

I was hoping to get 1.5 but somehow the trailing zeroes are not truncated. If instead of 0\{1,\} I explicitly write 0 or 000000 etc, it chops off the zeroes as entered, but obviously I need it to be dynamic.

What's wrong with 0\{1,\} ?

Upvotes: 9

Views: 7801

Answers (8)

grenade
grenade

Reputation: 32179

nothing wrong with previous answers, but here's another approach that should work in places where awk/bc/grep/sed aren't available.

all it does is trim the last character if it is a "0" until it is something other than a "0".

decimal="1.50000000000000000000"
echo ${decimal}
while [ "${decimal: -1}" = "0" ]; do
    decimal=${decimal::-1}
done
echo ${decimal}

Upvotes: 0

Matthew
Matthew

Reputation: 59

Here's my take. It removes leading zeros, and then if there is a decimal anywhere in the number, it also removes trailing zeros. This expression also works for numbers preceded or followed by space characters if present.

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

Upvotes: 0

Vasyl Shumskyi
Vasyl Shumskyi

Reputation: 143

One of the handy way to trim off trailing zeroes of a floating number is grep --only-matching option:

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

-o, --only-matching

Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Upvotes: 0

NeronLeVelu
NeronLeVelu

Reputation: 10039

echo "3/2" | bc -l | sed '/\./ s/\.\{0,1\}0\{1,\}$//'
  • remove trailing 0 IF there is a decimal separator
  • remove the separator if there are only 0 after separator also (assuming there is at least a digit before like BC does)

Upvotes: 16

Pedro Lobito
Pedro Lobito

Reputation: 98901

You can use printf for that:

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

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 203393

@anubhava has the right reason for your failed command, but just use awk instead:

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

Upvotes: 2

fedorqui
fedorqui

Reputation: 289645

Why don't you just set the number of digits you want with 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

I recommend you to go through man bc, since it contains many interesting ways to present your result.

Upvotes: 13

anubhava
anubhava

Reputation: 785108

$ must not be escaped and quote sed pattern:

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

Upvotes: 6

Related Questions