Handling python numbers by adding dot

8

I'm doing a simple code to convert meters to millimeters, what would be the best way to handle the result. Ex: 1000 in 1,000

Code:

valor_m = int(input("Digite um valor em metros: "))
valor_mm = valor_m * 1000

print "Valor em milimetros: %i mm." % valor_mm
    
asked by anonymous 08.03.2014 / 01:23

3 answers

7

As you can see in documentation , to use formatting with homes of thousands using the character , , just the following code:

'{0:,}'.format(num_int)

If you want to modify , by . :

'{0:,}'.format(num_int).replace(',','.')

This only applies to the version of 2.7+. From this SOEN response , you can do this for older versions by using locale.format () , as follows:

import locale
locale.setlocale(locale.LC_ALL, '') #pega o local da máquina e seta o locale
locale.format('%d', num_int, 1)

This will grab the location tab. In the case of Brazil, for example, it will be . , in the case of some countries, like the US, it will be , . Remember that it is possible to change the second parameter to the desired location.

Example with question code

Python 2.7 +

Code:

valor_m = int(input("Digite um valor em metros: ")) #se for 2.x deve ser raw_input ao invés de input
valor_mm = valor_m * 1000

resultado = '{0:,}'.format(valor_mm).replace(',','.') #Aqui coloca os pontos
print (resultado)

Input and output:

input:  2345
output: 2.345.000

Python 2.6 -

Code:

import locale
valor_m = int(raw_input("Digite um valor em metros: "))
valor_mm = valor_m * 1000

locale.setlocale(locale.LC_ALL, '') #pega o local da máquina e seta o locale
resultado = locale.format('%d', valor_mm, 1)
print resultado

Input and output:

input: 2345
output:
   'Portuguese_Brazil.1252' #Caso esteja interpretador no modo interativo
   2.345.000
    
08.03.2014 / 02:35
2

Recursive function:

def milhar(s, sep): # s = string, sep pode ser '.' ou ','
     return s if len(s) <= 3 else milhar(s[:-3], sep) + sep + s[-3:]
    
25.03.2014 / 03:56
0

Try using locale specifications.
Use the "grouping" and "thousands_sep" keys for LC_NUMERIC by specifying the thousands separator.

link

    
08.03.2014 / 02:36