Aiman
Aiman

Reputation: 123

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

Upvotes: 12

Views: 3873

Answers (4)

jabellcu
jabellcu

Reputation: 688

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

Upvotes: 1

geekosaur
geekosaur

Reputation: 61467

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

:%s/(\d+\.\d\d)\d+/\1/g

Upvotes: 5

Raimondi
Raimondi

Reputation: 5303

Using just VimL:

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

Upvotes: 19

Pontus
Pontus

Reputation: 1689

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

:perldo s/(\d+\.\d+)/sprintf "%.2f", $1/eg

Upvotes: 13

Related Questions