On Jan 13, 11:15 am, "Christian Brabandt" <[email protected]> wrote:
> On Thu, January 13, 2011 10:50 am, rameo wrote:
> > Is it possible to round numbers within vim?
>
> > I use this command to find numbers in my text with decimals:
>
> > :%s/\(\d\{1,}\)\(\,\)\(\d\{1,}\)/   xxx   /g
>
> > I would like to replace "xxx" with
>
> > if decimal >= ,5  --> round up and remove decimals
> > p.e. 4,5 --> 5
>
> > if decimal < ,5 --> round down and remove decimals.
> > p.e. 4,4 --> 4
>
> > but I don't know how to insert this in above substitute command.
> > Can anyone help me?
>
> This can be done like this:
> :%s/.../\=float2nr(round(str2float(substitute(submatch(1), ',', '.', ''))))
> this looks a little bit ugly, but you need first to replace your , by a
> dot so it can be successfully converted to a float, than round the float
> and convert it back to an integer.
>
> However, I think, your search regex can be simplified a bit to something
> like this:
> \d\+,\d\+
> and you don't even need to group this expression, since you can use
> submatch(0) to replace the whole matching pattern.
>
> So put it all together like this:
> :%s/\d\+,\d\+/\=float2nr(round(str2float(substitute(submatch(1), ',', '.',
> ''))))/g
>
> (this is one line, in case the mail get's mangled)
>
> regards,
> Christian

Thank you very much.
I changed submatch(1) to submatch(0), now it works fine.
With submatch(1) it replaced the numbers with "0".
I'll read more about float2nr, its new for me.
Thanks again Christian.

Rameo

-- 
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

Reply via email to