How to know if a converted string to float is really a float number ?

13 views
Skip to first unread message

Ni Va

unread,
Jan 17, 2020, 1:29:38 PM1/17/20
to vim_use
HI,

According to str2float help, I have tried this :

'3,3e+004'->substitute(',', '.', 'g')->str2float() which return 33000 number.

According to good conversion in this case it is a float num but if I replace by cases where it is not a well form of num that no have to be converted. 


'3,3e+00.4'->substitute(',', '.', 'g')->str2float() which return ????  there is a dot char in exp...
'3,3e+0O4'->substitute(',', '.', 'g')->str2float() which return ????  there is char 'O' out of zero


How to prevent unnecessary conversion ?

Thank you

Tony Mechelynck

unread,
Jan 17, 2020, 2:28:48 PM1/17/20
to vim_use
I tried the same examples, and in these last two cases I get 3.3 which
is to be expected since the conversion stops as soon as an input
character is found which would make the input invalid for a Float,
i.e., str2float('3.3e+00.4') interprets '3.3e+00' and converts it to
3.3 ; and str2float('3.3e+0O4') interprets '3.3e+0' and converts it to
3.3 — in both of these cases, trailing garbage is silently
disregarded.

In the first ("valid") case I get 33000.0 which is the number
expressed as a Float, not an (integer) Number.

If you can devise a regular expression covering what your input can
legitimately be, you could wrap the whole sequence of methods in an =~
or similar conditional (see :help expr-=~).


Best regards,
Tony.

Ni Va

unread,
Jan 18, 2020, 3:00:58 PM1/18/20
to vim_use
Ok Tony so I will prevent with regular expression that fit to float number. It seems well optimized.
Thank you
Reply all
Reply to author
Forward
0 new messages