Quick help needed: how to format an integer ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • durumdara@mailpont.hu

    #1

    Quick help needed: how to format an integer ?

    Hi !

    I need to convert some integer values.

    "1622" ->"1 622"

    or

    "10001234" -> ""10.001.23 4""

    So I need thousand separators.

    Can anyone helps me with a simply solution (like %xxx) ?

    Thanx for it: dd

    Ps:
    Now I use this proc:

    def toths(i):
    s=str(i)
    l=[]
    ls=len(s)
    for i in range(ls):
    c=s[ls-i-1]
    if i%3==0 and i<>0:
    c=c+"."
    l.append(c)
    l.reverse()
    return "".join(l)



  • Diez B. Roggisch

    #2
    Re: Quick help needed: how to format an integer ?

    durumdara@mailp ont.hu wrote:[color=blue]
    > Hi !
    >
    > I need to convert some integer values.
    >
    > "1622" ->"1 622"
    >
    > or
    >
    > "10001234" -> ""10.001.23 4""
    >
    > So I need thousand separators.
    >
    > Can anyone helps me with a simply solution (like %xxx) ?[/color]

    The module locale does what you need, look at ist docs, especially


    locale.str
    locale.format


    Regards,

    Diez

    Comment

    • Paul Rubin

      #3
      Re: Quick help needed: how to format an integer ?

      "durumdara@mail pont.hu" <durumdara@mail pont.hu> writes:[color=blue]
      > "10001234" -> ""10.001.23 4""
      > So I need thousand separators.
      > Can anyone helps me with a simply solution (like %xxx) ?[/color]

      I think you're supposed to do a locale-specific conversion (I've never
      understood that stuff). You could also do something like this:
      [color=blue][color=green][color=darkred]
      >>> def f(n):[/color][/color][/color]
      if n < 0: return '-' + f(-n)
      if n < 1000: return '%d' % n
      return f(n//1000) + '.' + '%03d' % (n%1000)
      [color=blue][color=green][color=darkred]
      >>> f(3900900090090 9090000009)[/color][/color][/color]
      '39.009.000.900 .909.090.000.00 9'[color=blue][color=green][color=darkred]
      >>> f(39802183)[/color][/color][/color]
      '39.802.183'[color=blue][color=green][color=darkred]
      >>> f(3008)[/color][/color][/color]
      '3.008'[color=blue][color=green][color=darkred]
      >>> f(0)[/color][/color][/color]
      '0'[color=blue][color=green][color=darkred]
      >>> f(-9898239839)[/color][/color][/color]
      '-9.898.239.839'[color=blue][color=green][color=darkred]
      >>> f(12345)[/color][/color][/color]
      '12.345'

      Comment

      Working...