Reply to message «Re: rounding numbers», sent 14:21:20 13 January 2011, Thursday by rameo:
> > 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)
This expression can be easily simlified using printf builtin:
:%s/\d\+,\d\+/\=printf("%.0f", str2float(substitute(submatch(0),',','.','')))/g
The fact that float will be rounded (not truncated) is mentioned in
documentation (`man 3 printf', in vim doc this is omitted), so I assume it to
be
stable behavior. You may test it yourself though: ``echo printf('%.0f', 1.5)''
prints 2, ``echo printf('%.0f', 1.4)'' prints 1. Note that with printf you may
round to arbitrary precision, not only to integer as with `round()'.
Original message:
> 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
signature.asc
Description: This is a digitally signed message part.
