def money_format_long(req, amount, code=None, currency=None): if amount is None: return '' cfg = req.registry.settings loc = req.current_locale if currency is not None: code = currency.code if code is None: code = cfg.get('netprofile.currency.default') if code is not None: if code in loc.currencies: return format_currency(amount, code, locale=loc, format='0.######## ¤¤¤', currency_digits=False) else: stdloc = req.locales[cfg.get('pyramid.default_locale_name', 'en')] if code in stdloc.currencies: return format_currency(amount, code, locale=stdloc, format='0.######## ¤¤¤', currency_digits=False) return format_decimal(amount, locale=loc, format='0.########')
def make_campaign_table_row(cls, id, start, end, target, bid, impressions, clicks, is_live, is_active, url, is_total): if impressions: cpm = format_currency(promote.cost_per_mille(bid, impressions), 'USD', locale=c.locale) else: cpm = '---' if clicks: cpc = format_currency(promote.cost_per_click(bid, clicks), 'USD', locale=c.locale) ctr = format_number(_clickthrough_rate(impressions, clicks)) else: cpc = '---' ctr = '---' return { 'id': id, 'start': start, 'end': end, 'target': target, 'bid': format_currency(bid, 'USD', locale=c.locale), 'impressions': format_number(impressions), 'cpm': cpm, 'clicks': format_number(clicks), 'cpc': cpc, 'ctr': ctr, 'live': is_live, 'active': is_active, 'url': url, 'csv': url + '.csv', 'total': is_total, }
def test_format_currency_long_display_name(): assert (numbers.format_currency(1099.98, 'USD', locale='en_US', format_type='name') == u'1,099.98 US dollars') assert (numbers.format_currency(1.00, 'USD', locale='en_US', format_type='name') == u'1.00 US dollar') assert (numbers.format_currency(1.00, 'EUR', locale='en_US', format_type='name') == u'1.00 euro') assert (numbers.format_currency(2, 'EUR', locale='en_US', format_type='name') == u'2.00 euros') # This tests that '{1} {0}' unitPatterns are found: assert (numbers.format_currency(1, 'USD', locale='sw', format_type='name') == u'dola ya Marekani 1.00') # This tests unicode chars: assert (numbers.format_currency(1099.98, 'USD', locale='es_GT', format_type='name') == u'dólares estadounidenses 1,099.98') # Test for completely unknown currency, should fallback to currency code assert (numbers.format_currency(1099.98, 'XAB', locale='en_US', format_type='name') == u'1,099.98 XAB') # Test for finding different unit patterns depending on count assert (numbers.format_currency(1, 'USD', locale='ro', format_type='name') == u'1,00 dolar american') assert (numbers.format_currency(2, 'USD', locale='ro', format_type='name') == u'2,00 dolari americani') assert (numbers.format_currency(100, 'USD', locale='ro', format_type='name') == u'100,00 de dolari americani')
def currency_format(context, value, currency='EUR', decimal=2): if value is None: value = 0.0 lang = translation.get_language() locale = context.get('locale', lang) if isinstance(value, six.string_types): symbol = get_currency_symbol(currency, locale=locale) if not symbol: symbol = currency return mark_safe('%s %s' % (value, symbol)) value = round(value, decimal) formatted = format_currency(value, currency, locale=locale) symbol = get_currency_symbol(currency, locale=locale) if not context.get('filter_country') and len(symbol) == 1: # When we have possibly mixed currencies, show three letter symbol # This improves alignment formatted = formatted.replace(symbol, currency) if decimal == 0: zero_amount = format_currency(0, currency, locale=locale) zero_decimals = zero_amount.replace(symbol, '').strip()[1:] formatted = formatted.replace(zero_decimals, '') return mark_safe(formatted.replace(' ', ' '))
def moneyfy(currency, amount): '''Format amount of money according to a locale''' if currency.lower() in ('€', 'eur'): return format_currency(int(amount), 'EUR', locale='en_GB').split('.')[0] elif currency.lower() in ('£', 'gbp'): return format_currency(int(amount), 'GBP', locale='en_GB').split('.')[0] return amount
def money_format(req, amount, code=None, prefix=None, suffix=None, currency=None): if amount is None: return '' cfg = req.registry.settings loc = req.current_locale if currency is not None: code = currency.code prefix = currency.prefix suffix = currency.suffix if code is None: code = cfg.get('netprofile.currency.default') if code is None: formatted = format_decimal(amount, locale=loc) elif code in loc.currencies: formatted = format_currency(amount, code, locale=loc) else: stdloc = req.locales[cfg.get('pyramid.default_locale_name', 'en')] if code in stdloc.currencies: formatted = format_currency(amount, code, locale=stdloc) else: formatted = format_decimal(amount, locale=loc) ret = [] if prefix: ret.append(prefix) ret.append(formatted) if suffix: ret.append(suffix) return '\xa0'.join(ret)
def currency_string(value, currency): """Takes a value and currency code and uses babel to properly format the currency into a localized string""" if value < 0: return "-" + format_currency(abs(value), currency) else: return format_currency(value, currency)
def test_format_currency_format_type(): assert (numbers.format_currency(1099.98, 'USD', locale='en_US', format_type="standard") == u'$1,099.98') assert (numbers.format_currency(0, 'USD', locale='en_US', format_type="standard") == u'$0.00') assert (numbers.format_currency(1099.98, 'USD', locale='en_US', format_type="accounting") == u'$1,099.98') assert (numbers.format_currency(0, 'USD', locale='en_US', format_type="accounting") == u'$0.00') with pytest.raises(numbers.UnknownCurrencyFormatError) as excinfo: numbers.format_currency(1099.98, 'USD', locale='en_US', format_type='unknown') assert excinfo.value.args[0] == "'unknown' is not a known currency format type" assert (numbers.format_currency(1099.98, 'JPY', locale='en_US') == u'\xa51,100') assert (numbers.format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES') == u'1.100') assert (numbers.format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False) == u'\xa51,099.98') assert (numbers.format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False) == u'1.099,98')
def list_splits(trans): """Returns a string with a list of splits for the given transaction (trans)""" temp = "" for split in trans.splits: if split.reconcile_state == "y": temp +="\t* " elif split.reconcile_state == "c": temp +="\t! " else: temp += "\t" temp += "{:60s}\t".format(full_acc_name(split.account)) if split.account.commodity != trans.currency and args.posting_cost == True: temp += "{:f} {} @@ {}".format(split.quantity, split.account.commodity, format_currency( abs(split.value), str(trans.currency))) elif split.account.commodity != trans.currency and args.posting_cost == False: temp += "{:f} {} @ {}".format(split.quantity, split.account.commodity, format_currency( abs(split.commodity_price), str(trans.currency))) else: temp += "{}".format(currency_string(split.value, str(trans.currency))) if split.memo: temp += "\t; {}".format(split.memo) temp += "\n" return temp
def _render_price(self, price): return format_currency(price, self.currency, locale=session.lang or 'en_GB')
def get_price_formatted(self): return format_currency(self.price, CURRENCY.upper(), locale="de_DE")
def get_price_locale(self): """Return the price as a nicely localised string for the locale.""" price, currency, locale = self._price() return numbers.format_currency(price, currency, locale=locale)
) amount = int(input()) return amount except ValueError: print("That wasn't a number.") return ask_amount(a_country, b_country) print("Welcome to CurrencyConvert PRO 2000\n") for index, country in enumerate(countries): print(f"#{index} {country['name']}") user_country = ask_country( "\nWhere are you from? Choose a country by number.\n") target_country = ask_country("\nNow choose another country.\n") amount = ask_amount(user_country, target_country) from_code = user_country['code'] to_code = target_country['code'] currency_request = requests.get( f"{currency_url}{from_code}-to-{to_code}-rate?amount={amount}") currency_soup = BeautifulSoup(currency_request.text, "html.parser") result = currency_soup.find("input", {"id": "cc-amount-to"}) if result: result = result['value'] amount = format_currency(amount, from_code, locale="ko_KR") result = format_currency(result, to_code, locale="ko_KR") print(f"{amount} is {result}")
def render(cls, registration): # XXX: Use event locale once we have such a setting return format_currency(registration.price, registration.currency, locale='en_GB')
def test_group_separator(self): self.assertEqual( '29567.12', numbers.format_decimal(29567.12, locale='en_US', group_separator=False)) self.assertEqual( '29567,12', numbers.format_decimal(29567.12, locale='fr_CA', group_separator=False)) self.assertEqual( '29567,12', numbers.format_decimal(29567.12, locale='pt_BR', group_separator=False)) self.assertEqual( u'$1099.98', numbers.format_currency(1099.98, 'USD', locale='en_US', group_separator=False)) self.assertEqual( u'101299,98\xa0€', numbers.format_currency(101299.98, 'EUR', locale='fr_CA', group_separator=False)) self.assertEqual( '101299.98 euros', numbers.format_currency(101299.98, 'EUR', locale='en_US', group_separator=False, format_type='name')) self.assertEqual( u'25123412\xa0%', numbers.format_percent(251234.1234, locale='sv_SE', group_separator=False)) self.assertEqual( u'29,567.12', numbers.format_decimal(29567.12, locale='en_US', group_separator=True)) self.assertEqual( u'29\u202f567,12', numbers.format_decimal(29567.12, locale='fr_CA', group_separator=True)) self.assertEqual( u'29.567,12', numbers.format_decimal(29567.12, locale='pt_BR', group_separator=True)) self.assertEqual( u'$1,099.98', numbers.format_currency(1099.98, 'USD', locale='en_US', group_separator=True)) self.assertEqual( u'101\u202f299,98\xa0\u20ac', numbers.format_currency(101299.98, 'EUR', locale='fr_CA', group_separator=True)) self.assertEqual( u'101,299.98 euros', numbers.format_currency(101299.98, 'EUR', locale='en_US', group_separator=True, format_type='name')) self.assertEqual( u'25\xa0123\xa0412\xa0%', numbers.format_percent(251234.1234, locale='sv_SE', group_separator=True))
def ind_currency(curr): curr_str = format_currency(curr, 'INR', locale='en_IN').replace(u'\xa0', u' ') return(remove_decimal(curr_str))
def process(titles): placeholders = [{ "str": "*CD*", "field": "charge/date" }, { "str": "*CP*", "field": "charge/lender/organisation" }] for title_idx, title in enumerate(titles): if not title['updated_at']: titles[title_idx]['updated_at'] = title['created_at'] for price_idx, price in enumerate(title['price_history']): titles[title_idx]['price_history'][price_idx][ 'price_pretty'] = numbers.format_currency( price['amount'] / 100, price['currency_code']).replace(".00", "") date_pretty = datetime.fromtimestamp( price['date']).strftime('%d %B %Y') titles[title_idx]['price_history'][price_idx][ 'date_pretty'] = date_pretty date_full_pretty = datetime.fromtimestamp( price['date']).strftime('%d %B %Y %H:%M:%S') titles[title_idx]['price_history'][price_idx][ 'date_full_pretty'] = date_full_pretty for restriction_idx, restriction in enumerate(title['restrictions']): if 'charge' in restriction: titles[title_idx]['charges'].append(restriction['charge']) charge_id = str(title_idx) + str(restriction_idx) titles[title_idx]['restrictions'][restriction_idx]['charge'][ 'html_id'] = charge_id for placeholder in placeholders: fields = placeholder['field'].split('/') restriction_temp = restriction for field in fields: if field in restriction_temp: if field == 'date': date_obj = datetime.strptime( restriction_temp[field], '%Y-%m-%dT%H:%M:%S.%f') value = datetime.strftime(date_obj, '%d %B %Y') else: value = restriction_temp[field] restriction_temp = value else: restriction_temp = None break if restriction_temp: text = restriction['restriction_text'].replace( placeholder['str'], str(restriction_temp)) titles[title_idx]['restrictions'][restriction_idx][ 'restriction_text'] = text return titles
def __init__(self, *args, **kwargs): nav_buttons = [ NavButton(_('overview'), '/advertising'), NavButton( _('getting started'), '/wiki/selfservenew?utm_source=advertising&utm_medium=button&utm_term=getting%20started&utm_campaign=buttons' ), NavButton( _('audience'), '/wiki/mediakit?utm_source=advertising&utm_medium=button&utm_term=audience&utm_campaign=buttons' ), NavButton( _('best practices'), '/wiki/brandiquette?utm_source=advertising&utm_medium=button&utm_term=best%20practices&utm_campaign=buttons' ), NavButton( _('help center'), '/wiki/selfserve?utm_source=advertising&utm_medium=button&utm_term=help%20center&utm_campaign=buttons' ), NavButton( _('manage ads'), '/promoted?utm_source=advertising&utm_medium=button&utm_term=manage%20ads&utm_campaign=buttons' ), ] self.create_ad_url = '/promoted/new_promo?utm_source=advertising&utm_medium=button&utm_term=create%20ads&utm_campaign=buttons' self.nav_menu = NavMenu(nav_buttons, type='flatlist', base_path='', css_class='advertising-menu', separator=None).render() sections = SelfServeContent.get_all(return_dict=True) self.banner = sections.get('banner') self.info = sections.get('info') self.advertisers = sections.get('advertisers') self.subreddit = sections.get('subreddit') self.help = sections.get('help') blurbs = SelfServeBlurb.get_all(return_dict=True) if 'platform' in blurbs: min_cpm = min([ g.cpm_selfserve_collection.decimal, g.cpm_selfserve.decimal, g.cpm_selfserve_geotarget_metro.decimal, ]) formatted_min_cpm = format_currency(min_cpm, 'USD', locale=c.locale) formatted_min_bid = format_currency(g.min_promote_bid, 'USD', locale=c.locale) blurbs['platform'].text = blurbs['platform'].text.replace( '[min_promote_bid]', formatted_min_bid).replace('[cpm_selfserve]', formatted_min_cpm) self.blurbs = blurbs.values() self.advertiser_logos = SelfServeAdvertiser.get_all() self.quotes = SelfServeQuote.get_all() self.help_text = None try: self.help_text = WikiPage.get(Frontpage, g.wiki_page_selfserve_help).content except NotFound: pass Templated.__init__(self, *args, **kwargs)
def test_format_currency_long_display_name_all(): for locale_code in localedata.locale_identifiers(): assert numbers.format_currency( 1, 'USD', locale=locale_code, format_type='name').find('1') > -1 assert numbers.format_currency( '1', 'USD', locale=locale_code, format_type='name').find('1') > -1
def parse_result(conf, num, _pass): return num if _pass else format_currency(num, conf.currency)
def render_base_price(self): return format_currency(self.base_price, self.currency, locale=session.lang or 'en_GB')
def render_price(self): return format_currency(self.price, self.registration.currency, locale=session.lang or 'en_GB')
def format_home_currency(value, locale=None): value = parse_decimal_string(value) return format_currency(value, currency=settings.SHOOP_HOME_CURRENCY, locale=locale or get_current_babel_locale())
import os from babel.numbers import format_currency from function import parsing_country_code, parsing_exchange_rate, parsing_tag, print_list from check import input_check, number_to_code os.system("clear") """ Use the 'format_currency' function to format the output of the conversion format_currency(AMOUNT, CURRENCY_CODE, locale="ko_KR" (no need to change this one)) """ tr = parsing_country_code() result_list = parsing_tag(tr) print_list(result_list) first = 0 second = 0 print("Where are you from? Choose a country by number.") first = input_check(result_list) first_code = number_to_code(result_list, first) print("Now choose another country.") second = input_check(result_list) second_code = number_to_code(result_list, second) print(f"How many {result_list[first-1][2]} do you want to convert to {result_list[second-1][2]}?") target = input_check(result_list, True) try: rate = parsing_exchange_rate(first_code, second_code, target)
def review_sales_agreement(): # save case ref in session so that its available on error redirects if request.args.get('case_reference'): session['case_reference'] = str(request.args.get('case_reference')) # form post if request.method == 'POST': try: title_id = request.form['title_id'] # api to fetch buyer's conveyancer details url = current_app.config[ 'CONVEYANCER_API_URL'] + '/titles/' + title_id + '/sales-agreement' agreement_res = requests.get( url, headers={'Accept': 'application/json'}) agreement_obj = agreement_res.json() agreement_approval_data = { "action": "approve", "signatory": agreement_obj['buyer_conveyancer'] } # approve agreement api call url = current_app.config[ 'CONVEYANCER_API_URL'] + '/titles/' + title_id + '/sales-agreement' response = requests.put(url, data=json.dumps(agreement_approval_data), headers={ 'Accept': 'Application/JSON', 'Content-Type': 'Application/JSON' }) if response.status_code == 200: return redirect(url_for('conveyancer_admin.case_list')) else: return redirect( url_for('conveyancer_admin.review_sales_agreement', error_message='Error: ' + response.text)) except Exception as e: return str(e) if request.method == 'GET': cases_details = {} # get case details url = current_app.config[ 'CASE_MANAGEMENT_API_URL'] + '/cases/' + session['case_reference'] case_details_res = requests.get( url, params={ "embed": "counterparty_id,client," "counterparty_conveyancer_contact_id,assigned_staff" }, headers={'Accept': 'application/json'}) if case_details_res.status_code == 200: cases_details = case_details_res.json() # if title number is not updated in the case redirect to case list if cases_details['title_number']: title_id = cases_details['title_number'] else: return redirect( url_for( 'conveyancer_admin.case_list', error_message='Error: Title not found in the case')) if cases_details['case_type'] == "sell": fetch_case_details("seller", "buyer", cases_details) else: fetch_case_details("buyer", "seller", cases_details) # make API call to fetch agreement values url = '{0}/titles/{1}/sales-agreement'.format( current_app.config['CONVEYANCER_API_URL'], cases_details['title_number']) agreement_details_response = requests.get( url, headers={'Accept': 'application/json'}) if agreement_details_response.status_code == 200: agreement_detail = agreement_details_response.json() obj_date = datetime.strptime(agreement_detail['completion_date'], '%Y-%m-%dT%H:%M:%S') agreement_detail['completion_date'] = datetime.strftime( obj_date, '%d %B %Y %H:%M') if agreement_detail['latest_update_date']: update_date = datetime.strptime( agreement_detail['latest_update_date'], '%Y-%m-%dT%H:%M:%S.%f') agreement_detail[ 'latest_update_date_time'] = datetime.strftime( update_date, '%d/%m/%Y %H:%M:%S') else: agreement_detail['latest_update_date_time'] = "" agreement_detail['purchase_price'] = numbers.format_currency( agreement_detail['purchase_price'], agreement_detail['purchase_price_currency_code']) agreement_detail['deposit'] = numbers.format_currency( agreement_detail['deposit'], agreement_detail['deposit_currency_code']) agreement_detail['balance'] = numbers.format_currency( agreement_detail['balance'], agreement_detail['balance_currency_code']) agreement_detail[ 'deposit_currency_code'] = numbers.get_currency_symbol( agreement_detail['deposit_currency_code']) agreement_detail[ 'balance_currency_code'] = numbers.get_currency_symbol( agreement_detail['balance_currency_code']) agreement_detail[ 'contents_price_currency_code'] = numbers.get_currency_symbol( agreement_detail['contents_price_currency_code']) agreement_detail[ 'purchase_price_currency_code'] = numbers.get_currency_symbol( agreement_detail['purchase_price_currency_code']) return render_template('app/admin/review_sales_agreement.html', agreement_details=agreement_detail, title_details=cases_details, title_id=title_id, admin=True) else: return render_template( 'app/admin/review_sales_agreement.html', error_message="Title agreement does not exist", admin=True)
def currency(self, number, currency): """Return a number in the given currency formatted for the locale. """ return format_currency(number, currency, locale=self.locale)
def format_currency(self, n, currency=None, format=None): return format_currency( n, format=format, currency=currency or getattr(self, 'default_currency', 'USD'), locale=get_locale_name(self.request))
def load_view_purchase_form(self): for index in range(1, 9): self.menubar.entryconfig(index, state=tk.DISABLED) self.show_menu(MainForm.is_admin_user) self.update_username() self.reload_lookup() # ********** Sub Containers ********* top_container = tk.Frame(self.content_container, padx=2, pady=1, relief=tk.RIDGE, bg=self.clr_yellow) top_container.pack(fill='both', expand=True, side=tk.TOP) bottom_container = tk.Frame(self.content_container, padx=2, pady=1, relief=tk.RIDGE, bg=self.clr_yellow) bottom_container.pack(fill='both', expand=True, side=tk.TOP) # top_container elements top_button_container = tk.Frame(top_container, bd=2, relief=tk.RIDGE, bg=self.clr_yellow) top_button_container.pack(fill='both', expand=True, side=tk.TOP) purchase_tree_container = tk.Frame(top_container, bd=2, pady=3, bg=self.clr_yellow, relief=tk.RIDGE) purchase_tree_container.pack(fill='both', expand=True, side=tk.TOP) # bottom_container elements purchase_details_container = tk.Frame(bottom_container, bd=2, relief=tk.RIDGE, bg=self.clr_yellow) purchase_details_container.pack(fill='both', expand=True, side=tk.LEFT) purchase_summary_container = tk.Frame(bottom_container, bd=2, relief=tk.RIDGE, bg=self.clr_yellow) purchase_summary_container.pack(fill='both', expand=True, anchor='w', side=tk.RIGHT) purchase_summary_tree_container = tk.Frame(bottom_container, bd=2, relief=tk.RIDGE, bg=self.clr_yellow) purchase_summary_tree_container.pack(fill='both', expand=True, side=tk.RIGHT) # ********** top_button_container elements ********* lbl_from_date = tk.Label(top_button_container, text='From Date:', bg=self.clr_yellow) lbl_from_date.grid(row=0, column=0, sticky="nw", padx=1, pady=1) self.from_date = DateEntry(top_button_container, date_pattern='yyyy-mm-dd', background='yellow', foreground='black', borderwidth=2, width=10) self.from_date.grid(row=1, column=0, sticky="sw", padx=2, pady=1, ipady=3) lbl_to_date = tk.Label(top_button_container, text='To Date:', bg=self.clr_yellow) lbl_to_date.grid(row=0, column=1, sticky="nw", padx=1, pady=1) self.to_date = DateEntry(top_button_container, date_pattern='yyyy-mm-dd', background='yellow', foreground='black', borderwidth=2, width=10) self.to_date.grid(row=1, column=1, sticky="sw", padx=2, pady=1, ipady=3) lbl_search_product_code = tk.Label(top_button_container, text="Product Code:", bg=self.clr_yellow) lbl_search_product_code.grid(row=0, column=2, columnspan=3, sticky="nw", padx=1, pady=1) self.ety_filter_product_code_1 = MaxLengthEntry(top_button_container, maxlength=3, width=4, textvariable=self.var_search_product_code_1) self.ety_filter_product_code_1.grid(row=1, column=2, sticky="nw", padx=2, pady=2, ipady=5) self.ety_filter_product_code_1.bind('<Return>', lambda event: self.validate_entry(event, 3)) self.ety_filter_product_code_2 = MaxLengthEntry(top_button_container, maxlength=3, width=4, textvariable=self.var_search_product_code_2) self.ety_filter_product_code_2.grid(row=1, column=3, sticky="nw", padx=2, pady=2, ipady=5) self.ety_filter_product_code_2.bind('<Return>', lambda event: self.validate_entry(event, 3)) self.ety_filter_product_code_3 = MaxLengthEntry(top_button_container, maxlength=2, width=3, textvariable=self.var_search_product_code_3) self.ety_filter_product_code_3.grid(row=1, column=4, sticky="nw", padx=2, pady=2, ipady=5) self.ety_filter_product_code_3.bind('<Return>', lambda event: self.validate_entry(event, 2)) self.ety_filter_product_code_4 = MaxLengthEntry(top_button_container, maxlength=4, width=5, textvariable=self.var_search_product_code_4) self.ety_filter_product_code_4.grid(row=1, column=5, sticky="nw", padx=2, pady=2, ipady=5) self.ety_filter_product_code_4.bind('<Return>', lambda event: self.validate_entry(event, 4)) filter_lbl_garment_name = tk.Label(top_button_container, text="Garment Name:", bg=self.clr_yellow) filter_lbl_garment_name.grid(row=0, column=6, sticky="nw", padx=1, pady=1) self.ety_filter_garment_name = AutocompleteEntry(top_button_container, width=15, completevalues=self.garment_list) self.ety_filter_garment_name.grid(row=1, column=6, sticky="nw", padx=2, pady=1, ipady=6) self.ety_filter_garment_name.bind("<Return>", lambda event: self.filter_purchase(event)) filter_lbl_product_name = tk.Label(top_button_container, text="Name:", bg=self.clr_yellow) filter_lbl_product_name.grid(row=0, column=7, sticky="nw", padx=1, pady=1) self.ety_filter_product_name = AutocompleteEntry(top_button_container, width=18, completevalues=self.product_name_list) self.ety_filter_product_name.grid(row=1, column=7, sticky="nw", padx=2, pady=1, ipady=6) self.ety_filter_product_name.bind("<Return>", lambda event: self.filter_purchase(event)) filter_lbl_product_type = tk.Label(top_button_container, text="Type:", bg=self.clr_yellow) filter_lbl_product_type.grid(row=0, column=8, sticky="nw", padx=1, pady=1) self.ety_filter_product_type = AutocompleteEntry(top_button_container, width=20, completevalues=self.product_type_list) self.ety_filter_product_type.grid(row=1, column=8, sticky="nw", padx=2, pady=1, ipady=6) self.ety_filter_product_type.bind("<Return>", lambda event: self.filter_purchase(event)) filter_lbl_product_size = tk.Label(top_button_container, text="Size:", bg=self.clr_yellow) filter_lbl_product_size.grid(row=0, column=9, sticky="nw", padx=1, pady=1) self.ety_filter_product_size = AutocompleteEntry(top_button_container, width=12, completevalues=self.product_size_list) self.ety_filter_product_size.grid(row=1, column=9, sticky="nw", padx=2, pady=1, ipady=6) self.ety_filter_product_size.bind("<Return>", lambda event: self.filter_purchase(event)) filter_lbl_product_price = tk.Label(top_button_container, text="Price:", bg=self.clr_yellow) filter_lbl_product_price.grid(row=0, column=10, sticky="nw", padx=1, pady=1) self.ety_filter_product_sell_price = AutocompleteEntry(top_button_container, width=10, completevalues=self.product_sell_price_list) self.ety_filter_product_sell_price.grid(row=1, column=10, sticky="nw", padx=2, pady=1, ipady=6) self.ety_filter_product_sell_price.bind("<Return>", lambda event: self.filter_purchase(event)) chk_include_date = tk.Checkbutton(top_button_container, text='Include Date', variable=self.var_include_date, onvalue=1, offvalue=0, bg=self.clr_yellow) chk_include_date.grid(row=0, column=11, columnspan=2, sticky="sw", padx=2, pady=1) btn_filter = tk.Button(top_button_container, text="Apply Filter", bg=self.clr_fuchsia, fg='white', command=self.filter_purchase) btn_filter.grid(row=1, column=11, sticky="sw", padx=2, pady=1) btn_clear_filter = tk.Button(top_button_container, text="Clear", command=self.reload_purchase) btn_clear_filter.grid(row=1, column=12, sticky="news", padx=2, pady=1) # ********** tree_containers elements ********* header = ('#', 'PURCHASE_DATE', 'GARMENT_NAME', 'PRODUCT_CODE', 'PRODUCT_NAME', 'PRODUCT_TYPE', 'SIZE', 'PRICE', 'QTY', 'AMOUNT', '') self.purchase_tree = ttk.Treeview(purchase_tree_container, columns=header, height=8, show="headings", selectmode="browse") vsb = ttk.Scrollbar(purchase_tree_container, orient="vertical", command=self.purchase_tree.yview) hsb = ttk.Scrollbar(purchase_tree_container, orient="horizontal", command=self.purchase_tree.xview) self.purchase_tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set) style = ttk.Style() style.configure("Treeview.Heading", font=('Calibri', 12)) style.configure("Treeview", font=('Calibri', 12), rowheight=25) self.purchase_tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set) self.purchase_tree.grid(column=0, row=0, sticky='nsew', in_=purchase_tree_container) vsb.grid(column=1, row=0, sticky='ns', in_=purchase_tree_container) hsb.grid(column=0, row=1, sticky='ew', in_=purchase_tree_container) purchase_tree_container.grid_columnconfigure(0, weight=1) purchase_tree_container.grid_rowconfigure(0, weight=1) self.purchase_tree.heading("0", text="#") self.purchase_tree.heading("1", text="PURCHASE_DATE") self.purchase_tree.heading("2", text="GARMENT_NAME") self.purchase_tree.heading("3", text="PRODUCT_CODE") self.purchase_tree.heading("4", text="PRODUCT_NAME") self.purchase_tree.heading("5", text="PRODUCT_TYPE") self.purchase_tree.heading("6", text="SIZE") self.purchase_tree.heading("7", text="PRICE") self.purchase_tree.heading("8", text="QTY") self.purchase_tree.heading("9", text="AMOUNT") self.purchase_tree.column(0, anchor='center', width="20") self.purchase_tree.column(1, anchor=tk.W, width="120") self.purchase_tree.column(2, anchor=tk.W, width="200") self.purchase_tree.column(3, anchor=tk.W, width="120") self.purchase_tree.column(4, anchor=tk.W, width="140") self.purchase_tree.column(5, anchor=tk.W, width="180") self.purchase_tree.column(6, anchor='center', width="80") self.purchase_tree.column(7, anchor=tk.E, width="80") self.purchase_tree.column(8, anchor='center', width="50") self.purchase_tree.column(9, anchor=tk.E, width="120") self.purchase_tree.column(10, anchor='center', width="2") self.reload_purchase() numeric_cols = ['#', 'PRICE', 'QTY', 'AMOUNT'] for col in header: if col in numeric_cols: self.purchase_tree.heading(col, text=col, command=lambda _col=col: self.sort_treeview( self.purchase_tree, _col, numeric_sort=True, reverse=False)) else: self.purchase_tree.heading(col, text=col, command=lambda _col=col: self.sort_treeview( self.purchase_tree, _col, numeric_sort=False, reverse=False)) self.purchase_tree.tag_configure("evenrow", background='#fbefcc') self.purchase_tree.tag_configure("oddrow", background='white', foreground='black') self.purchase_tree.bind('<<TreeviewSelect>>', self.on_tree_select) # ********** Purchase Details ********* purchase_details_container.grid_columnconfigure(0, weight=1) purchase_details_container.grid_columnconfigure(3, weight=1) lbl_purchase_details = tk.Label(purchase_details_container, text="Product Details", bg=self.clr_blueiris, fg="white") lbl_purchase_details.grid(row=0, column=1, columnspan=2, sticky="news", padx=3, pady=3) lbl_purchase_details.config(font=("Calibri bold", 12)) lbl_purchase_date = tk.Label(purchase_details_container, text="Purchase Date: ", bg=self.clr_yellow) lbl_purchase_date.grid(row=1, column=1, sticky="nw", padx=3, pady=1) ety_purchase_date = tk.Entry(purchase_details_container, width=15, textvariable=self.var_purchase_date, state='disabled') ety_purchase_date.grid(row=1, column=2, sticky="nw", padx=3, pady=1) lbl_garment_name = tk.Label(purchase_details_container, text="Garment Name: ", bg=self.clr_yellow) lbl_garment_name.grid(row=2, column=1, sticky="nw", padx=3, pady=1) ety_garment_name = tk.Entry(purchase_details_container, textvariable=self.var_garment_name, state='disabled') ety_garment_name.grid(row=2, column=2, sticky="nw", padx=3, pady=1) lbl_product_code = tk.Label(purchase_details_container, text="Product Code: ", bg=self.clr_yellow) lbl_product_code.grid(row=3, column=1, sticky="nw", padx=3, pady=1) ety_product_code = tk.Entry(purchase_details_container, width=15, textvariable=self.var_product_code, state='disabled') ety_product_code.grid(row=3, column=2, sticky="nw", padx=3, pady=1) lbl_product_name = tk.Label(purchase_details_container, text="Product Name: ", bg=self.clr_yellow) lbl_product_name.grid(row=4, column=1, sticky="nw", padx=3, pady=1) ety_product_name = tk.Entry(purchase_details_container, textvariable=self.var_product_name, state='disabled') ety_product_name.grid(row=4, column=2, sticky="nw", padx=3, pady=1) lbl_product_type = tk.Label(purchase_details_container, text="Product Type: ", bg=self.clr_yellow) lbl_product_type.grid(row=5, column=1, sticky="nw", padx=3, pady=1) ety_product_type = tk.Entry(purchase_details_container, textvariable=self.var_product_type, state='disabled') ety_product_type.grid(row=5, column=2, sticky="nw", padx=3, pady=1) lbl_product_size = tk.Label(purchase_details_container, text="Size: ", bg=self.clr_yellow) lbl_product_size.grid(row=6, column=1, sticky="nw", padx=3, pady=1) ety_product_size = tk.Entry(purchase_details_container, width=10, textvariable=self.var_product_size, state='disabled') ety_product_size.grid(row=6, column=2, sticky="nw", padx=3, pady=1) lbl_selling_price = tk.Label(purchase_details_container, text="Price: ", bg=self.clr_yellow) lbl_selling_price.grid(row=7, column=1, sticky="nw", padx=3, pady=1) ety_selling_price = tk.Entry(purchase_details_container, width=10, textvariable=self.var_selling_price, state='disabled') ety_selling_price.grid(row=7, column=2, sticky="nw", padx=3, pady=1) lbl_quantity = tk.Label(purchase_details_container, text="Quantity: ", bg=self.clr_yellow) lbl_quantity.grid(row=8, column=1, sticky="nw", padx=3, pady=1) ety_quantity = tk.Entry(purchase_details_container, width=5, textvariable=self.var_quantity, state='disabled') ety_quantity.grid(row=8, column=2, sticky="nw", padx=3, pady=1) lbl_amount = tk.Label(purchase_details_container, text="Amount: ", bg=self.clr_yellow) lbl_amount.grid(row=9, column=1, sticky="nw", padx=3, pady=1) ety_amount = tk.Entry(purchase_details_container, width=10, textvariable=self.var_amount, state='disabled') ety_amount.grid(row=9, column=2, sticky="nw", padx=3, pady=1) purchase_summary_container.grid_columnconfigure(0, weight=1) purchase_summary_container.grid_columnconfigure(2, weight=1) lbl_purchase_summary = tk.Label(purchase_summary_container, text="Purchase Summary", bg=self.clr_blueiris, fg="white") lbl_purchase_summary.grid(row=0, column=1, sticky="news", padx=3, pady=3) lbl_purchase_summary.config(font=("Calibri bold", 14)) lbl_purchase_date = tk.Label(purchase_summary_container, text="Purchase Date:", bg=self.clr_yellow) lbl_purchase_date.grid(row=1, column=1, sticky="nw", padx=3, pady=1) ety_purchase_date = tk.Entry(purchase_summary_container, width=12, textvariable=self.var_purchase_date, state='disabled') ety_purchase_date.grid(row=2, column=1, sticky="nw", padx=3, pady=1, ipady=6) lbl_total_quantity = tk.Label(purchase_summary_container, text="Total Quantity:", bg=self.clr_yellow) lbl_total_quantity.grid(row=3, column=1, sticky="nw", padx=3, pady=1) ety_total_quantity = tk.Entry(purchase_summary_container, width=12, textvariable=self.var_total_quantity, state='disabled') ety_total_quantity.grid(row=4, column=1, sticky="nw", padx=3, pady=1, ipady=6) lbl_total_amount = tk.Label(purchase_summary_container, text="Total Amount:", bg=self.clr_yellow) lbl_total_amount.grid(row=5, column=1, sticky="nw", padx=3, pady=1) ety_total_amount = tk.Entry(purchase_summary_container, width=12, textvariable=self.var_total_amount, state='disabled') ety_total_amount.grid(row=6, column=1, sticky="nw", padx=3, pady=1, ipady=6) self.var_total_amount.set(format_currency(0, 'INR', locale='en_IN')) btn_get_purchase_summary = tk.Button(purchase_summary_container, text="Get Purchase Summary", bg=self.clr_fuchsia, fg='white', command=self.get_purchase_summary) btn_get_purchase_summary.grid(row=7, column=1, sticky="news", padx=3, pady=10) # monthly_summary_tree_container summary_tree = tk.Frame(purchase_summary_tree_container, pady=1, relief=tk.RIDGE, bg=self.clr_yellow) summary_tree.pack(fill='both', expand=True, side=tk.RIGHT) header = ('#', 'PRODUCT_CODE', 'PRODUCT', 'TYPE', 'SIZE', 'PRICE', 'QTY', 'AMOUNT', '') self.summary_tree = ttk.Treeview(summary_tree, columns=header, height=5, show="headings", selectmode="browse") vsb = ttk.Scrollbar(summary_tree, orient="vertical", command=self.summary_tree.yview) hsb = ttk.Scrollbar(summary_tree, orient="horizontal", command=self.summary_tree.xview) self.summary_tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set) self.summary_tree.grid(column=0, row=0, sticky='nsew') vsb.grid(column=1, row=0, sticky='ns') hsb.grid(column=0, row=1, sticky='ew') summary_tree.grid_columnconfigure(0, weight=1) summary_tree.grid_rowconfigure(0, weight=1) self.summary_tree.heading("0", text="#") self.summary_tree.heading("1", text="PRODUCT_CODE") self.summary_tree.heading("2", text="PRODUCT") self.summary_tree.heading("3", text="TYPE") self.summary_tree.heading("4", text="SIZE") self.summary_tree.heading("5", text="PRICE") self.summary_tree.heading("6", text="QTY") self.summary_tree.heading("7", text="AMOUNT") self.summary_tree.heading("8", text="") self.summary_tree.column(0, anchor='center', minwidth=30, width=30) self.summary_tree.column(1, anchor=tk.W, minwidth=50, width=120) self.summary_tree.column(2, anchor=tk.W, minwidth=80, width=100) # Product self.summary_tree.column(3, anchor=tk.W, minwidth=130, width=130) # Type self.summary_tree.column(4, anchor='center', minwidth=50, width=50) # Size self.summary_tree.column(5, anchor=tk.E, minwidth=60, width=60) # Price self.summary_tree.column(6, anchor='center', minwidth=40, width=40) # Qty self.summary_tree.column(7, anchor=tk.E, minwidth=80, width=80) # Amount self.summary_tree.column(8, anchor='center', width=1) self.summary_tree["displaycolumns"] = (0, 1, 2, 3, 4, 5, 6, 7, 8) numeric_cols = ['#', 'PRICE', 'QTY', 'AMOUNT'] for col in header: if col in numeric_cols: self.summary_tree.heading(col, text=col, command=lambda _col=col: self.sort_treeview( self.summary_tree, _col, numeric_sort=True, reverse=False)) else: self.summary_tree.heading(col, text=col, command=lambda _col=col: self.sort_treeview( self.summary_tree, _col, numeric_sort=False, reverse=False)) self.summary_tree.tag_configure("evenrow", background='#fbefcc') self.summary_tree.tag_configure("oddrow", background='white', foreground='black')
def as_currency(value): return format_currency(value, 'EUR', locale='de_DE')
def add_new_charge_restriction(): if request.args.get('case_reference'): session['case_reference'] = str(request.args.get('case_reference')) # get title number from case reference title_number = get_title_number(session['case_reference']) # if title number not found go to case list if not title_number: return redirect( url_for('conveyancer_admin.case_list', error_message='Error: Case has no title linked to it.')) # Form posted if request.method == 'POST': lender_party = { "organisation": current_app.config['BUYER_LENDER_PARTY_ORGANISATION'], "locality": current_app.config['BUYER_LENDER_PARTY_LOCALITY'], "country": current_app.config['BUYER_LENDER_PARTY_COUNTRY'] } if current_app.config.get('BUYER_LENDER_PARTY_STATE'): lender_party['state'] = current_app.config[ 'BUYER_LENDER_PARTY_STATE'] if current_app.config.get('BUYER_LENDER_PARTY_ORGANISATIONAL_UNIT'): lender_party['organisational_unit'] = current_app.config[ 'BUYER_LENDER_PARTY_ORGANISATIONAL_UNIT'] if current_app.config.get('BUYER_LENDER_PARTY_COMMON_NAME'): lender_party['common_name'] = current_app.config[ 'BUYER_LENDER_PARTY_COMMON_NAME'] data = { "restriction_id": "NA", "restriction_type": "CBCR", "restriction_text": request.form.get('restriction_text'), "consenting_party": lender_party, "signed_actions": "add", "date": request.form.get('date'), "charge": { "date": request.form.get('date'), "lender": lender_party, "amount": request.form.get('amount'), "amount_currency_code": request.form.get('amount_currency') } } try: url = current_app.config[ 'CONVEYANCER_API_URL'] + '/titles/' + title_number + '/restrictions' add_restriction_res = requests.post(url, data=json.dumps(data), headers={ 'Accept': 'application/json', 'Content-Type': 'Application/JSON' }) if add_restriction_res.status_code == 200: return redirect(url_for('conveyancer_admin.case_list')) else: if add_restriction_res.text: error_message = add_restriction_res.text else: error_message = "Error: Conveyancer API failed. Could not return a response." return redirect( url_for('conveyancer_admin.case_list', error_message=error_message)) except requests.exceptions.RequestException: return "Conveyancer API is down." else: # Fetch agreement completion date and purchase amount url = current_app.config[ 'CONVEYANCER_API_URL'] + '/titles/' + title_number + '/sales-agreement' agreement_res = requests.get(url, headers={'Accept': 'application/json'}) agreement_obj = agreement_res.json() title_charges_res = requests.get( current_app.config['CASE_MANAGEMENT_API_URL'] + '/restrictions', params={'type': 'CBCR'}, headers={'Accept': 'application/json'}) # get buyer lender name buyer_lender = "Gringott's Bank" title_charges = {} if title_charges_res.status_code == 200: title_charges = title_charges_res.json() # change date and amount formats for title_charge in title_charges: # assign the format the input date is in completion_date_obj = datetime.strptime( agreement_obj['completion_date'], '%Y-%m-%dT%H:%M:%S') title_charge['date_unformatted'] = datetime.strftime( completion_date_obj, '%Y-%m-%dT%H:%M:%S') title_charge['date'] = datetime.strftime( completion_date_obj, '%d %B %Y') title_charge['buyer_lender'] = buyer_lender title_charge['amount_currency'] = agreement_obj[ 'balance_currency_code'] title_charge['amount'] = agreement_obj["balance"] title_charge['amount_display'] = numbers.format_currency( agreement_obj["balance"], agreement_obj['balance_currency_code']) placeholders = [{ "placeholder_str": "*CD*", "field": "date" }, { "placeholder_str": "*CP*", "field": "buyer_lender" }] # loop over placeholders to replace them for placeholder in placeholders: if placeholder['field'] in title_charge: restriction_text = title_charge['restriction_text'] title_charge[ 'restriction_text'] = restriction_text.replace( placeholder['placeholder_str'], str(title_charge[placeholder['field']])) return render_template('app/admin/add_charge_restriction.html', title_charge=title_charge, admin=True)
def main(): # store employees created in session, reset on exit employee_list = [] print("Welcome to the Employee Benefits Calculator!") user_input = "" while True: print(""" Main Menu: - To enter an employee's benefits, press 1 - To preview currently entered employees and dependents, press 2 - To Exit and show all employees + calculated benefits, press 3 """) user_input = int(input("Please enter a selection number: ")) if user_input == 1: curr_employee = Employee() # need to ensure employee + dependent names only contain letters while True: emp_first_name = input("Please enter employee's first name: ") emp_last_name = input("Please enter employee's last name: ") if emp_first_name.isalpha() and emp_last_name.isalpha(): break print("first and/or last name is invalid, please enter again") emp_dep_count = int( input("Please enter number of dependents for this employee: ")) if emp_dep_count > 0: dep_count = 0 while dep_count < emp_dep_count: curr_dependent = Dependent() dep_first_name = dep_last_name = "" while True: dep_first_name = input( "Please enter dependent {}'s first name: ".format( dep_count + 1)) dep_last_name = input( "Please enter dependent {}'s last name: ".format( dep_count + 1)) if dep_first_name.isalpha() and dep_last_name.isalpha( ): break print( "first and/or last name is invalid, please enter again" ) curr_dependent.first_name = dep_first_name curr_dependent.last_name = dep_last_name curr_employee.add_dependant(curr_dependent) dep_count += 1 curr_employee.first_name = emp_first_name curr_employee.last_name = emp_last_name employee_list.append(curr_employee) elif user_input == 2: output_info(employee_list) elif user_input == 3: break else: print("Invalid choice, please try again. \n") total_benefit_cost = calculate_employee_benefits_total(employee_list) total_benefit_cost_str = format_currency(total_benefit_cost, "USD", locale="en_US", format="$#,###.00") print("Total cost of benefits for all employees in this session is: " + total_benefit_cost_str)
import os import requests from bs4 import BeautifulSoup from babel.numbers import format_currency os.system("clear") """ Use the 'format_currency' function to format the output of the conversion format_currency(AMOUNT, CURRENCY_CODE, locale="ko_KR" (no need to change this one)) """ iban_url = "https://www.iban.com/currency-codes" transferwize_url = "https://transferwise.com/gb/currency-converter" def get_table(): countries = [] request = requests.get(iban_url) soup = BeautifulSoup(request.text, "html.parser") table = soup.find("table") rows = table.find_all("tr")[1:] for row in rows: items = row.find_all("td") name = items[0].text code = items[2].text if name and code: if name != "No universal currency": country = {'name': name.capitalize(), 'code': code} countries.append(country)
print('Total number of active users: ' + str(len(active_list))) inactive_list = [] for row in data: if row['isActive'] == False: inactive_list.append(row['isActive']) print('Total number of inactive users: ' + str(len(inactive_list))) balance = 0 for row in data: balance += Decimal(sub(r'[^\d.]', '', row['balance'])) avg = balance / len(data) print('Grand total balance for all users: ' + format_currency(balance, 'USD', locale='en_US')) print('Average balance for all users: ' + format_currency(avg, 'USD', locale='en_US')) balance_list = [] for row in data: balance_list.append(row['balance']) for row in data: if row['balance'] == min(balance_list): print('User with lowest balance: ' + row['name']) for row in data: if row['balance'] == max(balance_list): print('User with highest balance: ' + row['name'])
def en_dollars(v): return format_currency(v, 'CAD', locale='en_CA')
def format_numbers(number): """Format results to look like $""" formatted_number = format_currency(number, 'USD', locale='en_US') return formatted_number
def charge_removal_consent(title_number): # Form posted if request.method == 'POST': url = current_app.config[ 'LENDER_API_URL'] + '/titles/' + title_number + '/restrictions' title_restriction_res = requests.delete( url, headers={'Accept': 'application/json'}) if title_restriction_res.status_code == 200: return redirect(url_for('lender_admin.list')) else: return redirect( url_for('lender_admin.charge_removal_consent', title_number=title_number, error_message='Error: ' + title_restriction_res.text)) # fetch title address titles_res = requests.get(current_app.config['LENDER_API_URL'] + '/titles/' + title_number, headers={'Accept': 'application/json'}) title_address = "" if titles_res.status_code == 200: title = titles_res.json() title_address = title['title']['address'] # CBCR is of type charge and ORES is type generic url = current_app.config[ 'LENDER_API_URL'] + '/titles/' + title_number + '/restrictions' title_restriction_res = requests.get( url, params={'type': 'CBCR'}, headers={'Accept': 'application/json'}) error_message = None if not title_restriction_res.status_code == 200: title_restrictions = None if title_restriction_res.text: error_message = title_restriction_res.text else: error_message = "Error: Lender API failed. Could not return a response." else: title_restrictions = title_restriction_res.json() placeholders = [{ "placeholder_str": "**RT**", "field": "restriction_type" }, { "placeholder_str": "**RD**", "field": "date" }, { "placeholder_str": "**RA**", "field": "charge/amount" }, { "placeholder_str": "**RO**", "field": "lender" }, { "placeholder_str": "*CD*", "field": "date" }, { "placeholder_str": "*CP*", "field": "lender" }] # loop over titles to replace placeholders in the restriction text for title_restriction in title_restrictions: title_restriction['lender'] = title_restriction[ 'consenting_party']['organisation'] # change date format date_obj = datetime.strptime(title_restriction['charge']['date'], '%Y-%m-%dT%H:%M:%S.%f') title_restriction['date'] = datetime.strftime(date_obj, '%d %B %Y') # change amount format if exists if 'charge' in title_restriction: title_restriction['charge'][ 'amount'] = numbers.format_currency( title_restriction['charge']['amount'], title_restriction['charge']['amount_currency_code']) # loop over placeholders to replace them for placeholder in placeholders: fields = placeholder['field'].split("/") # store in temp variable to avoid overriding restriction_temp = title_restriction # loop over fields if it is an object for value in fields: if value in restriction_temp: restriction_temp = restriction_temp[value] else: restriction_temp = None # if first element of fields isn't in the restrictions then the rest would'nt be either, # so break break if restriction_temp: restriction_text = title_restriction['restriction_text'] title_restriction[ 'restriction_text'] = restriction_text.replace( placeholder['placeholder_str'], str(restriction_temp)) return render_template('app/admin/discharge_consent.html', title_restrictions=title_restrictions, title_number=title_number, title_address=title_address, error_message=error_message)
print("\nNow choose another country.\n") last_country = ask_code() while last_country == None: last_country = ask_code() def ask_convert_money(): print( f"\nHow many {first_country['code']} do you want to convert to {last_country['code']}?" ) try: convert_money = float(input()) return convert_money except: print("That wasn't a number.") convert_money = ask_convert_money() while type(convert_money) != float: convert_money = ask_convert_money() url_transferwise = f"https://transferwise.com/gb/currency-converter/{first_country['code']}-to-{last_country['code']}-rate?amount={convert_money}" result = requests.get(url_transferwise) soup = BeautifulSoup(result.text, "html.parser") table = float(soup.find("span", {"class": "text-success"}).string) result_money = table * convert_money print(format_currency(convert_money, first_country['code']), "is", format_currency(result_money, last_country['code']))
def fr_dollars(v): return format_currency(v, 'CAD', locale='fr_CA')
def test_format_currency_precision(input_value, expected_value): # Test precision conservation. assert numbers.format_currency(decimal.Decimal(input_value), 'USD', locale='en_US') == expected_value