1

I have created a currency app, where the user could key in the value of the home country, and select from the home currency to foreign currency.

from kivy.core.text import LabelBase
from kivymd.app import MDApp
from kivy.lang.builder import Builder
from kivy.core.window import Window
from kivymd.uix.floatlayout import MDFloatLayout
from kivy.uix.button import Button
from kivymd.uix.menu import MDDropdownMenu
from kivy.metrics import dp  
from decimal import *
from forex_python.converter import CurrencyRates

Window.size=(400, 500)

class DropdownButton(MDFloatLayout, Button):
    pass

class CurrencyConvertor(MDApp):
    
    try:
        c = CurrencyRates()
        rates = c.get_rates('USD')  
        print(rates)
    except:
        print('Connection Error!') 
  
##################################################
   
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.screen = Builder.load_string(kv)
        
##################################################
#################### to items #################### 
        c = CurrencyRates()       
        to_items = [
            {
                "viewclass": "OneLineListItem",
                "text": f"{i}",
                "height": dp(56),
                "on_release": lambda x=f"{i}": self.set_to(x),
            # } for i in range(5)
             } for i in self.rates.keys()
        ]
        self.to_menu = MDDropdownMenu(
            caller=self.screen.ids.to_currency,
            items=to_items,
            position="auto",
            width_mult=4,
        )
        self.to_menu.bind()
        
 ################################################## 
 ################### from items ###################     
        c = CurrencyRates()
        from_items = [
            {
                "viewclass": "OneLineListItem",
                "text": f"{i}",
                "height": dp(56),
                "on_release": lambda x=f"{i}": self.set_from(x),
            } for i in self.rates.keys()
           # } for i in range(5)
        ]
        self.from_menu = MDDropdownMenu(
            caller=self.screen.ids.from_currency,
            items=from_items,
            position="auto",
            width_mult=4,
        )
        self.from_menu.bind()
        
##################################################
##################### set to ##################### 
    def set_to(self, text_item):
        if text_item != self.screen.ids.from_currency.text:
            self.screen.ids.to_currency.text = text_item
            self.to_menu.dismiss()
    
##################################################
#################### set from ####################
    def set_from(self, text_item):
        if text_item != self.screen.ids.to_currency.text:
            self.screen.ids.from_currency.text = text_item
            self.from_menu.dismiss()
            
##################################################
    def build(self):
        return self.screen
    
    
##################################################    
    def convert(self):
    
        c = CurrencyRates(force_decimal=True)
        amount = int(self.screen.ids.amount.text)
        from_currency = self.screen.ids.from_currency.text
        to_currency = self.screen.ids.to_currency.text
        converted_amount = c.convert(from_currency, to_currency, Decimal(amount))
        #print(converted_amount)
        self.root.ids.result.text = f"{amount} {from_currency} = {converted_amount} {to_currency}"
       
kv = '''
#<KvLang>
MDFloatLayout:
    md_bg_color: 1,1,1,1
    MDLabel:
        text: 'Currency Convertor'
        pos_hint: {'center_x': .5, 'center_y': .9}
        halign: 'center'
        font_name: 'media/poppins-bold'
        front_size: '32sp'
    MDFloatLayout:
        size_hint: .85,.2
        pos_hint: {'center_x': 0.5,'center_y': 0.7}
        MDLabel:
            text: "Enter Amount"
            pos_hint: {'center_x': 0.5, 'center_y': 0.85}
            font_name: 'media/poppins-medium'
            font_size: '18sp'
        MDFloatLayout:
            size_hint_y: .5
            pos_hint: {'center_x': .5, 'center_y':.38}
            canvas.before:
                Color:
                    rgb: 210/255, 210/255, 210/255, 1
                Line:
                    width: 1.2
                    rounded_rectangle:self.x, self.y, self.width, self.height, 6, 6, 6, 6, 100
            TextInput:
                id: amount
                text: ''
                size_hint: 1, None
                pos_hint: {'center_x': .5, 'center_y': .5}
                height: self.minimum_height
                font_name: 'media/poppins-medium'        
                font_size: '18sp'
                hint_text_color: 170/255, 170/255, 170/255, 1
                background_color: 1, 1, 1, 0
                padding: 13
                cursor_color: 0,0,0,1
                multiline: False
                
    MDFloatLayout:
        size_hint: .85, .2
        pos_hint: {'center_x': .5, 'center_y': .46}
        MDFloatLayout:
            pos_hint: {'center_x': .6, 'center_y': .5} 
            MDLabel:
                text: "From"
                pos_hint: {'center_x': 0.5, 'center_y': 0.85}
                font_name: 'media/poppins-medium'
                font_size: '18sp'
                
            DropdownButton:                
                id: from_currency
                text: 'EUR'
                size_hint: .25, .5
                pos_hint: {'center_x': .125, 'center_y':.38}
                background_color: 0, 0, 0, 0
                color: 0, 0, 0, 1 
                font_size: '20sp'
                font_name: 'media/poppins-medium'
                on_release: app.from_menu.open()
                # on_release: print('Hello')
                canvas.before:
                    Color:
                        rgb: 210/255, 210/255, 210/255, 1
                    Line:
                        width: 1.2
                        rounded_rectangle:self.x, self.y, self.width, self.height, 6, 6, 6, 6, 100
        Image:
            source: 'media/arrow.png'
            size_hint: .35, .35
            pos_hint: {'center_x': .5, 'center_y': .38} 
            
        MDFloatLayout:
            pos_hint: {'center_x':1.15, 'center_y': .5} 
            MDLabel:
                text: "To"
                pos_hint: {'center_x': 0.5, 'center_y': 0.85}
                font_name: 'media/poppins-medium'
                font_size: '18sp'
                
            DropdownButton:                
                id: to_currency
                text: 'USD'
                size_hint: .25, .5
                pos_hint: {'center_x': .125, 'center_y':.38}
                background_color: 0,0,0,0
                color: 0,0,0,1
                font_name: 'media/poppins-medium'
                font_size: '20sp'
                on_release: app.to_menu.open()
                canvas.before:
                    Color:
                        rgb: 210/255, 210/255, 210/255, 1
                    Line:
                        width: 1.2
                        rounded_rectangle:self.x, self.y, self.width, self.height, 6, 6, 6, 6, 100
                        
    MDLabel:
        id: result
        text: ''
        pos_hint: {'center_x': .5, 'center_y': .3}
        halign: 'center'
        font_name: 'media/poppins-medium'
        font_size: '18sp'
        
    Button: 
        text: 'Get Exchange Rate'
        font_name: 'media/poppins-medium'
        size_hint: .85, .12
        font_size: '18sp'
        pos_hint: {'center_x': .5, 'center_y': .15}
        background_color: 1,1,1,0
        color: 1,1,1,1
        # on_release: print('result')
        on_release: app.convert()
        canvas.before:
            Color: 
                rgb: 71/255, 104/255, 237/255, 1
            RoundedRectangle:
                size: self.size
                pos: self.pos
                radius: [6]
#<KvLang>
'''

CurrencyConvertor().run()
LabelBase.register(name="Poppins", fn_regular="media/Poppins-Regular.ttf")     
    

It could print out all the currency conversions. Example: when I input the value of USD 10,000, require to convert it to EUR, the result is shown as below: 10000 EUR = 10131.0000 USD

What can I do, if I need to format the result: 1) a comma for each,000 both USD and EUR? and 2) specify 2 decimals placed in the USD? So it can be read easily without distraction

Loh Boon How
  • 123
  • 7
  • Does this answer your question? [Currency formatting in Python](https://stackoverflow.com/questions/320929/currency-formatting-in-python) – ThePhi Aug 17 '22 at 10:17

2 Answers2

1

Use an f-string:

inp = '10131.0000 USD'

num, curr = inp.split()
out = f'{float(num):,.2f} {curr}'

print(out) # 10,131.00 USD
The Thonnu
  • 3,578
  • 2
  • 8
  • 30
0

for commas you can use format.

commas = lambda x: f'{x:,}'

print(list(map(commas, [1000000, 22992992, 399999990])))


['1,000,000', '22,992,992', '399,999,990']

the same for decimals.

decimals = lambda x: f'{x:.2f}'


print(list(map(decimals,[10131.0000, 494949.29000])))

['10131.00', '494949.29']

the same with list comprehensions

print([commas(x) for x in [1000000, 22992992, 399999990]])
['1,000,000', '22,992,992', '399,999,990']

print([decimals (x) for x in [10131.0000, 494949.29000]])
['10131.00', '494949.29']
LetzerWille
  • 5,355
  • 4
  • 23
  • 26