Fandom

Vim Tips Wiki

Align numbers at decimal point

1,624pages on
this wiki
Add New Page
Talk0 Share

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Duplicate tip

This tip is very similar to the following:

These tips need to be merged – see the merge guidelines.

Tip 893 Printable Monobook Previous Next

created 2005 · complexity intermediate · author Michael Fitz · version 5.7


Suppose you have some numbers in an ugly format:

123
2.5678
-13.44
100.5
  +47.11

You want to have them nice aligned with 5 decimals written out.

First, we align any line left to the beginning:

:%s§^\s*§§

123
2.5678
-13.44
100.5
+47.11

Now we split at the decimal-point (if any) and shift the fractional part wide to the right and add five '0' at the end (because we want 5 fractional digts).

:%s§\([-+]\?\d\+\)\.\?\(\d*$\)§\1                        !\200000§

123                        !00000
2                        !567800000
-13                        !4400000
100                        !500000
+47                        !1100000

This tricky substitue aligns the fractional part at column 15:

:%s§\%15c\s*!§!§

123           !00000
2             !567800000
-13           !4400000
100           !500000
+47           !1100000

Now we shift the integral part back by exchanging it with leading spaces (and replacing '!' by decimal-point):

:%s§\(^\S*\)\(\s*\)!§\2\1.§

           123.00000
             2.567800000
           -13.4400000
           100.500000
           +47.1100000

Now we truncate each fractional part to 5 digits:

:%s§\%21c\d*§§

           123.00000
             2.56780
           -13.44000
           100.50000
           +47.11000

Finally we add a '+'-sign where it's missing:

:%s§\s\(\d\)§+\1§

          +123.00000
            +2.56780
           -13.44000
          +100.50000
           +47.11000

I usually use the (german) paragraph-sign '§' to surround the substitute-patterns, because this letter is very seldom used in any IT-related context.

CommentsEdit

See VimTip139 for AlignMaps which provides the \anum (actually <Leader>anum) to do something similar:

123
  2.5678
-13.44
100.5
+47.11

It doesn't append the zeros, just does a numeric alignment. \anum also handles the use of commas instead of periods, European style.


Also on Fandom

Random Wiki