Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,\} ?

like image 938
RocketNuts Avatar asked May 04 '15 15:05

RocketNuts


People also ask

How do I remove leading and trailing spaces from a string?

# Declare a variable, $myvar with a string data. `sed` command is another option to remove leading and trailing space or character from the string data. The following commands will remove the spaces from the variable, $myVar using `sed` command. Use sed ‘s/^ *//g’, to remove the leading white spaces.

How do I trim a string in Bash?

Sometimes it requires to remove characters from the starting and end of the string data which is called trimming. There is a built-in function named trim () for trimming in many standard programming languages. Bash has no built-in function to trim string data.

How do I do floating point arithmetic in Bash?

As noted by others, bash does not support floating point arithmetic, although you could fake it with some fixed decimal trickery, e.g. with two decimals: See Nilfred's answer for a similar but more concise approach. Besides the mentioned bc and awk alternatives there are also the following: print $ ( ( 1/3. ))

How does it remember trailing zeros?

It remembers any values beginning with 0., followed by zero or more 0 's, followed by 1 or more digits from 1-9, followed by zero or more 0 's. It then truncates the zero or more trailing 0 's. This allows you to parse out an arbitrary number of trailing zeros, and retain any arbitrarily low number greater than zero. regardless of how small it is.


1 Answers

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)
like image 169
NeronLeVelu Avatar answered Sep 20 '22 11:09

NeronLeVelu