format a number for output

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • abcd

    #1

    format a number for output

    if i have a number, say the size of a file, is there an easy way to
    output it so that it includes commas?

    for example:

    1890284

    would be:

    1,890,284

    I am looking for something builtin to python, not a third party lib.

    thanks

  • Marc 'BlackJack' Rintsch

    #2
    Re: format a number for output

    In <1154962511.485 221.229830@i3g2 000cwc.googlegr oups.com>, abcd wrote:
    if i have a number, say the size of a file, is there an easy way to
    output it so that it includes commas?
    >
    for example:
    >
    1890284
    >
    would be:
    >
    1,890,284
    I think this comes close:

    In [23]: import locale

    In [24]: locale.setlocal e(locale.LC_ALL , '')
    Out[24]: 'en_US.UTF-8'

    In [25]: locale.format(' %d', 1890284, True)
    Out[25]: '1,890,284'

    It's not always commas but whatever character is used to group thousands
    in the active locale.

    Ciao,
    Marc 'BlackJack' Rintsch

    Comment

    • BartlebyScrivener

      #3
      Re: format a number for output

      abcd wrote:
      if i have a number, say the size of a file, is there an easy way to
      output it so that it includes commas?
      >
      for example:
      >
      1890284
      >
      would be:
      >
      1,890,284
      see also this thread:

      http://tinyurl.com/qf6ew

      rd

      Comment

      • Paul Rubin

        #4
        Re: format a number for output

        "abcd" <codecraig@gmai l.comwrites:
        1890284
        >
        would be:
        >
        1,890,284
        "To iterate is human; to recurse, divine":

        def commafy(n):
        if n < 0: return '-' + commafy(-n)
        if n >= 1000: return '%s,%03d' % (commafy(n//1000), n % 1000)
        return '%s'% n

        I don't like the locale solution because of how messy locales are.

        Comment

        • BartlebyScrivener

          #5
          Re: format a number for output


          Paul Rubin wrote:
          "To iterate is human; to recurse, divine":
          >
          def commafy(n):
          if n < 0: return '-' + commafy(-n)
          if n >= 1000: return '%s,%03d' % (commafy(n//1000), n % 1000)
          return '%s'% n
          >
          I don't like the locale solution because of how messy locales are.
          That's a keeper!

          Thanks!

          rd

          Comment

          Working...