Replace formated float value trailing zeros with spaces

Hi,

After formatting some floating point values with “%8.4f” format, i got the following strings :

  0.0000
123.0000  
123.4500
123.0450
123.4560

Now, I want to remove trailing zeros and replace them with spaces to keep dot alignment, giving :

Case 1:

  0.0       
123.0
123.45  
123.045
123.456 

or, with integer display when appropriate

Case 2:

  0       
123
123.45  
123.045
123.456 

Currently, I came up with the following regex for case 2

 ("%8.4f" % x).gsub(/\.?0*$/) { |c| " " * c.size }

Still searching for a concise solution for case 1 !

Any ideas ?

I’m not sure if I got what you try to achieve (= replace all trailing zeros, except one after . ??).

Are you looking for ("%8.4f" % x).gsub(/(?<!\.)0+$/){ |c| " " * c.size } ?

@kjarex, wow, that’s it ! Thanks a lot.

1 Like