12

My regex is quite rusty. How could vim be used to change the precision of a decimal number.

For example:

Changing 30.2223221 8188.2121213212 to 30.22 8188.21

Aiman
  • 123
  • 1
  • 4

4 Answers4

18

Using just VimL:

:%s/\d\+\.\d\+/\=printf('%.2f',str2float(submatch(0)))/g

Raimondi
  • 5,163
  • 31
  • 39
13

It's likely possible using vim internal search/replace, but I would use "perldo":

:perldo s/(\d+\.\d+)/sprintf "%.2f", $1/eg
Pontus
  • 1,639
  • 2
  • 11
  • 6
  • I modified this regex to also work with negative numbers and e-notation: ([-]?\d+\.\d+(e[+-]\d)?) – Reimund Apr 25 '16 at 23:13
5

If you just want to truncate the last digit instead of rounding,

:%s/(\d+\.\d\d)\d+/\1/g
geekosaur
  • 59,309
  • 11
  • 123
  • 114
  • 1
    The above did not work for me, but adding a few slashes fixes it... :%s/\(\d\+\.\d\d\)\d\+/\1/g – Charles Mar 12 '13 at 19:38
1

Based on the previous answers, using VimL, for negative numbers and exponential notation:

:%s/\c\v[-]=\d+\.\d+(e[+-]\d+)=/\=printf('%.2f',str2float(submatch(0)))/g
jabellcu
  • 692
  • 8
  • 20