lua-users home
lua-l archive

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



I'm really surprised no-one's mentioned Lua 5.1's % operator?

Lua 5.1  Copyright (C) 1994-2006 Lua.org, PUC-Rio
> a= 1234.56
> b= a % 1000
> c= (a-b)/1000
> print( c..' '..b )
1 234.56


Michael Abbott kirjoitti 26.1.2006 kello 7.26:

On Wed, 2006-01-25 at 18:04 +0100, PA wrote:
On Jan 25, 2006, at 09:40, Zakaria wrote:

I'm a Lua newbie. What is the best way to do it?

Very brutal, there must be a better way :)

function self:formatNumber( aNumber, aLocale )
         if aNumber ~= nil then
                 local aString = tostring( math.floor( aNumber ) )

                 if aString:len() > 3 then
                         aString = aString:reverse()
                         aString = aString:gsub( "(%d%d%d)", "%1," )
                         aString = aString:reverse()

                         if aString:sub( 1, 1 ) == "," then
                                 aString = aString:sub( 2 )
                         end
                 end

                 return aString
         end

         return nil
end

Some alternatives:

http://www.bigbold.com/snippets/posts/show/693
http://www.rubygarden.org/ruby?NumericFormat

Very ugly!  Having originally come from South Africa, I shudder when I
see hard-coded separation like this.  In SA, we used the comma instead
of the period to display numbers (eg. 10,24 instead of 10.24). I think the most common thousand separation was 1 000,24 and I vaguely remember
seeing 1.000,24 a few times as well (I haven't lived there for some
time). A quick search tells me that Switzerland does something similar
(and reverts to the common period notation for currency).

It'd be really nice to see a locale-aware method of doing this :-)

- Mab