Search code examples
regexbashsedfloating-point

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


Solution

  • 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)