How to convert monetary number to extended number in Python

Asked

Viewed 3,274 times

-2

How can I convert a monetary number into an extended number using Python ?

  • 2

    The purpose of this site is not for people to make programs for you, but to answer questions about programming - https://answall.com/help/how-to-ask

  • @jsbueno do not see the question as at all wrong, Aliais vi similar questions https://answall.com/q/99460/3635 and https://answall.com/q/263365/3635, which I think .... Of course I partly agree with you, not for the same reasons, but in the sense that the question basically already has answers on the site, in other languages, but if it is algorithmic it would be enough to adapt. What would be worth a duplicate, of course I would have to put together a couple of questions, something to convert the monetary into a number and another to talk about the long.

  • @Jsbueno is not an entire program, it’s just a two-line orientation: >>>import locale >>>valueDecimal = locale.atof(valueCurrency[1:]). When so the important thing is not to answer but to give a direction.

  • I published and answered the question. While searching I found several similar questions but depended on a dictionary for each number and its respective description.

2 answers

4

Can be used num2words with the parameter lang=pt_BR to convert an integer to an extended number, an example that includes the format and addition of cent(s) or real(ais) in the returned string:

from num2words import num2words

def number_to_long_number(number_p):
    if number_p.find(',')!=-1:
        number_p = number_p.split(',')
        number_p1 = int(number_p[0].replace('.',''))
        number_p2 = int(number_p[1])
    else:
        number_p1 = int(number_p.replace('.',''))
        number_p2 = 0    

    if number_p1 == 1:
        aux1 = ' real'
    else:
        aux1 = ' reais'

    if number_p2 == 1:
        aux2 = ' centavo'
    else:
        aux2 = ' centavos'

    text1 = ''
    if number_p1 > 0:
        text1 = num2words(number_p1,lang='pt_BR') + str(aux1)
    else:
        text1 = ''

    if number_p2 > 0:
        text2 = num2words(number_p2,lang='pt_BR') + str(aux2) 
    else: 
        text2 = ''

    if (number_p1 > 0 and number_p2 > 0):
        result = text1 + ' e ' + text2
    else:
        result = text1 + text2

    return result

Exemplo de retorno

0

You can use a dictionary where the key will be the number and the value will be the number in full.

numero = {1:'um', 2:'dois', 3:'três'}

print(numero.get(1))
print(numero.get(2))
print(numero.get(3))

Exit:

um
dois
três

Browser other questions tagged

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