lua-users home
lua-l archive

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


On 31 August 2013 06:42, Coda Highland <chighland@gmail.com> wrote:
> On Fri, Aug 30, 2013 at 1:29 PM, Choonster TheMage
> <choonster.2010@gmail.com> wrote:
>> On 31 August 2013 06:14, Geoff Smith <spammealot1@live.co.uk> wrote:
>>> Hi
>>>
>>> I always seem to have difficulty with pattern matching in Lua, here is
>>> another example that has stumped me so far
>>>
>>> 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"
>>>
>>> I could of course write a function that iterates through the string from the
>>> back dropping zeros, but I thought there is probably a more elegant solution
>>> using Lua pattern matching functions.
>>>
>>> Can this be done neatly with pattern matching ? Thanks for any suggested
>>> code snippets
>>>
>>> Regards Geoff
>>>
>>>
>>>
>>
>> Try this pattern:
>>
>>     local stripped = fullNumber:match("^(%d*%.?0?%d-)0*$")
>>
>> Where fullNumber is the string containing the number that you want to
>> remove trailing zeroes from.
>>
>
> I have a hesitation on that solution -- if there isn't a decimal
> point, that's still going to truncate trailing zeroes, which is
> clearly incorrect behavior.
>
> /s/ Adam
>

It doesn't do that under Lua 5.1.5, 5.2.1 or LuaJIT 2.0.1

Running this code:

local function trim0( s )
    return s:match("^(%d*%.?0?%d-)0*$")
end

print( trim0 "123.450000000" )
print( trim0 "1234500" )
print( trim0 "12345.0" )

Gives this output:

123.45
1234500
12345.0

The first %d* should capture all digits when there's no decimal point,
since it's a greedy pattern item.