Welcome, guest | Sign In | My Account | Store | Cart

For many languages it is possible to use the locale module to format numbers. But there are at least three languages for which the locale.localeconv()['thousands_sep'] is empty: brazilian portuguese - 'pt_br', portuguese - 'pt' and spanish - 'es'.

The first function, format_positive_integer() will return the passed integer number as a string with the thousands group separator added.

The second function, format_number() much more generic, will accept any number, integer or float, positive or negative, and return a string with the thousands group separator and the desired precision.

Python, 35 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def format_positive_integer(number):

    l = list(str(number))
    c = len(l)
   
    while c > 3:
        c -= 3
        l.insert(c, '.')

    return ''.join(l)

def format_number(number, precision=0, group_sep='.', decimal_sep=','):

    number = ('%.*f' % (max(0, precision), number)).split('.')

    integer_part = number[0]
    if integer_part[0] == '-':
        sign = integer_part[0]
        integer_part = integer_part[1:]
    else:
        sign = ''
      
    if len(number) == 2:
        decimal_part = decimal_sep + number[1]
    else:
        decimal_part = ''
   
    integer_part = list(integer_part)
    c = len(integer_part)
   
    while c > 3:
        c -= 3
        integer_part.insert(c, group_sep)

    return sign + ''.join(integer_part) + decimal_part
Created by Clodoaldo Pinto Neto on Wed, 3 Jan 2007 (PSF)
Python recipes (4591)
Clodoaldo Pinto Neto's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks