lua-users home
lua-l archive

RE: pattern matching problem

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi Dirk

Whilst I liked the simplicity of the tonumber solution, I couldn't use that as it limits the number of significant digits it can cope with. For example

a=0.123456789012345678
print(string.format("%19.18f",a))

b="0.123456789012345678"
print(b)
print(trimzeros(b))

produces
0.123456789012345680

0.123456789012345678
0.12345678901235 <-- truncates to 15 digits

The more complex string pattern solutions do mean you can have unlimited number of digits.

Regards Geoff


> Date: 2013年8月31日 11:24:42 +0200
> From: dirk.laurie@gmail.com
> To: lua-l@lists.lua.org
> Subject: Re: pattern matching problem
>
> 2013年8月30日 Geoff Smith <spammealot1@live.co.uk>:
>
>
> > I am trying to trim a number string to remove non significant trailing
> > zeros. So for example
> >
> > "123.450000000" = "123.45"
> > "1234500" = "1234500"
> > "12345.00" = "12345.0"
>
> > Can this be done neatly with pattern matching ? Thanks for any suggested
> > code snippets
>
> If this is a purely academic exercise, i.e. gsub must be used and the output
> must follow the rules suggested by the three examples, there have been
> some ingenious replies.
>
> If it is merely a question of making output look intuitive, it is hard
> to beat this:
>
> function trimzeros(s) return tostring(tonumber(s)) end
>
> which throws in the bonus of checking that the input is a valid number string.
>

AltStyle によって変換されたページ (->オリジナル) /