Treat python numbers by adding dot

Asked

Viewed 5,124 times

8

I am making a simple code to convert meters into millimeters. What would be the best way to treat the result. Ex: 1000 or 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
  • I haven’t solved it yet, I just need to treat the result in value_mm to have a point every three digits, counting from right to left. How would this apply to the above code?

3 answers

9


As can be seen in documentation, to use thousands-square formatting using the character ,, the following code is sufficient:

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

If you want to modify the , for .:

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

This only goes for the version of 2.7+. From this point on response from the SOEN, it is possible to make older versions using the 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 take the location tab. In the case of Brazil, for example, will be the ., in the case of some countries, such as the US, the ,. 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
  • My goal is just to put one . every three numbers, counting from right to left. I still could not using the code above.

  • 1

    I’ll edit with your code to see if it fits your question better.

3

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:]

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.