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,\}
?
# 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.
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.
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. ))
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.
echo "3/2" | bc -l | sed '/\./ s/\.\{0,1\}0\{1,\}$//'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With