Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing the precision of numbers - regex vim

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

like image 703
Aiman Avatar asked Mar 04 '11 21:03

Aiman


4 Answers

Using just VimL:

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

like image 160
Raimondi Avatar answered Nov 02 '22 05:11

Raimondi


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

:perldo s/(\d+\.\d+)/sprintf "%.2f", $1/eg
like image 44
Pontus Avatar answered Nov 02 '22 03:11

Pontus


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

:%s/(\d+\.\d\d)\d+/\1/g
like image 5
geekosaur Avatar answered Nov 02 '22 03:11

geekosaur


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
like image 1
jabellcu Avatar answered Nov 02 '22 03:11

jabellcu