Python locale.currency() Examples

The following are 30 code examples of locale.currency(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module locale , or try the search function .
Example #1
Source File: cryptop.py    From cryptop with MIT License 6 votes vote down vote up
def get_price(coin, curr=None):
    '''Get the data on coins'''
    curr = curr or CONFIG['api'].get('currency', 'USD')
    fmt = 'https://min-api.cryptocompare.com/data/pricemultifull?fsyms={}&tsyms={}'

    try:
        r = requests.get(fmt.format(coin, curr))
    except requests.exceptions.RequestException:
        sys.exit('Could not complete request')

    try:
        data_raw = r.json()['RAW']
        return [(float(data_raw[c][curr]['PRICE']),
                 float(data_raw[c][curr]['HIGH24HOUR']),
                 float(data_raw[c][curr]['LOW24HOUR'])) for c in coin.split(',') if c in data_raw.keys()]
    except:
        sys.exit('Could not parse data') 
Example #2
Source File: app.py    From tradingview-trainer with MIT License 6 votes vote down vote up
def update_labels(self):

        # update all labels via tk StringVar()
        self.last_price_value.set(str(self.get_last_price()))
        self.current_position_pnl.set(str(self.get_position_pnl()) + '%')
        self.account_value_pnl.set(str(round(percent_change(get_account_value(), float(config.initial_amount)), 2)) + '%')
        self.current_position_value.set(str(get_position()['quantity']) + " @ " + str(get_position()['entry']))
        self.account_value_text.set(locale.currency(get_account_value(), grouping=True))
        self.ticker_value.set(self.get_ticker())

        # Update trade history box
        self.trade_history_list.delete(0, 'end')
        for trade in read_all():
            self.trade_history_list.insert(0, trade)

    # get last price via xpath 
Example #3
Source File: test_marks.py    From pytest-Quick-Start-Guide with MIT License 5 votes vote down vote up
def test_currency_br():
    assert locale.currency(10.5) == "R$ 10,50" 
Example #4
Source File: test_locale.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out) 
Example #5
Source File: functions.py    From docassemble with MIT License 5 votes vote down vote up
def currency_default(value, **kwargs):
    """Returns the value as a currency, according to the conventions of
    the current locale.  Use the optional keyword argument
    decimals=False if you do not want to see decimal places in the
    number, and the optional currency_symbol for a different symbol
    than the default.

    """
    decimals = kwargs.get('decimals', True)
    symbol = kwargs.get('symbol', None)
    ensure_definition(value, decimals, symbol)
    obj_type = type(value).__name__
    if obj_type in ['FinancialList', 'PeriodicFinancialList']:
        value = value.total()
    elif obj_type in ['Value', 'PeriodicValue']:
        if value.exists:
            value = value.amount()
        else:
            value = 0
    elif obj_type == 'DACatchAll':
        value = float(value)
    try:
        float(value)
    except:
        return ''
    the_symbol = None
    if symbol is not None:
        the_symbol = symbol
    elif this_thread.misc.get('currency symbol', None) not in (None, ''):
        the_symbol = this_thread.misc['currency symbol']
    elif language_functions['currency_symbol']['*'] is not currency_symbol_default:
        the_symbol = currency_symbol()
    if the_symbol is None:
        if decimals:
            return str(locale.currency(float(value), symbol=True, grouping=True))
        else:
            return currency_symbol() + locale.format_string("%d", int(float(value)), grouping=True)
    if decimals:
        return the_symbol + locale.format_string('%.' + str(server.daconfig.get('currency decimal places', 2)) + 'f', float(value), grouping=True)
    else:
        return the_symbol + locale.format_string("%d", int(float(value)), grouping=True) 
Example #6
Source File: functions.py    From docassemble with MIT License 5 votes vote down vote up
def currency_symbol_default(**kwargs):
    """Returns the currency symbol for the current locale."""
    return str(locale.localeconv()['currency_symbol']) 
Example #7
Source File: functions.py    From docassemble with MIT License 5 votes vote down vote up
def get_currency_symbol():
    """Returns the current setting for the currency symbol if there is
    one, and otherwise returns the default currency symbol.

    """
    symbol = this_thread.misc.get('currency symbol', None)
    if symbol is not None:
        return symbol
    return currency_symbol() 
Example #8
Source File: functions.py    From docassemble with MIT License 5 votes vote down vote up
def get_locale(*pargs):
    """Returns the current locale setting, or the current currency symbol
    if the argument is 'currency_symbol'.

    """
    if len(pargs) == 1 and pargs[0] == 'currency_symbol':
        return this_thread.misc.get('currency symbol', None)
    return this_thread.locale 
Example #9
Source File: functions.py    From docassemble with MIT License 5 votes vote down vote up
def set_locale(*pargs, **kwargs):
    """Sets the current locale.  See also update_locale()."""
    if len(pargs) == 1:
        this_thread.locale = pargs[0]
    if 'currency_symbol' in kwargs:
        this_thread.misc['currency symbol'] = kwargs['currency_symbol'] 
Example #10
Source File: test_locale.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out) 
Example #11
Source File: test_locale.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out) 
Example #12
Source File: test_locale.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out) 
Example #13
Source File: endpoints.py    From flask_jsondash with MIT License 5 votes vote down vote up
def singlenum():
    """Fake endpoint."""
    _min, _max = 10, 10000
    if 'sales' in request.args:
        val = locale.currency(float(rr(_min, _max)), grouping=True)
    else:
        val = rr(_min, _max)
    if 'negative' in request.args:
        val = '-{}'.format(val)
    return jsonify(data=val) 
Example #14
Source File: test_locale.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out) 
Example #15
Source File: test_locale.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out) 
Example #16
Source File: donation_tags.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def money(value):
    locale.setlocale(locale.LC_ALL, '')
    try:
        if not value:
            return locale.currency(0.0)
        return locale.currency(value, symbol=True, grouping=True)
    except ValueError:
        locale.setlocale(locale.LC_MONETARY, 'en_US.utf8')
        if not value:
            return locale.currency(0.0)
        return locale.currency(value, symbol=True, grouping=True) 
Example #17
Source File: test_marks.py    From pytest-Quick-Start-Guide with MIT License 5 votes vote down vote up
def test_currency_us():
    assert locale.currency(10.5) == "$10.50" 
Example #18
Source File: test_locale.py    From oss-ftp with MIT License 5 votes vote down vote up
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out) 
Example #19
Source File: test_locale.py    From BinderFilter with MIT License 5 votes vote down vote up
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out) 
Example #20
Source File: cryptop.py    From cryptop with MIT License 5 votes vote down vote up
def write_scr(stdscr, wallet, y, x):
    '''Write text and formatting to screen'''
    first_pad = '{:>{}}'.format('', CONFIG['theme'].getint('dec_places', 2) + 10 - 3)
    second_pad = ' ' * (CONFIG['theme'].getint('field_length', 13) - 2)
    third_pad =  ' ' * (CONFIG['theme'].getint('field_length', 13) - 3)

    if y >= 1:
        stdscr.addnstr(0, 0, 'cryptop v0.2.0', x, curses.color_pair(2))
    if y >= 2:
        header = '  COIN{}PRICE{}HELD {}VAL{}HIGH {}LOW  '.format(first_pad, second_pad, third_pad, first_pad, first_pad)
        stdscr.addnstr(1, 0, header, x, curses.color_pair(3))

    total = 0
    coinl = list(wallet.keys())
    heldl = list(wallet.values())
    if coinl:
        coinvl = get_price(','.join(coinl))

        if y > 3:
            s = sorted(list(zip(coinl, coinvl, heldl)), key=SORT_FNS[SORTS[COLUMN]], reverse=ORDER)
            coinl = list(x[0] for x in s)
            coinvl = list(x[1] for x in s)
            heldl = list(x[2] for x in s)
            for coin, val, held in zip(coinl, coinvl, heldl):
                if coinl.index(coin) + 2 < y:
                    stdscr.addnstr(coinl.index(coin) + 2, 0,
                    str_formatter(coin, val, held), x, curses.color_pair(2))
                total += float(held) * val[0]

    if y > len(coinl) + 3:
        stdscr.addnstr(y - 2, 0, 'Total Holdings: {:10}    '
            .format(locale.currency(total, grouping=True)), x, curses.color_pair(3))
        stdscr.addnstr(y - 1, 0,
            '[A] Add/update coin [R] Remove coin [S] Sort [C] Cycle sort [0\Q]Exit', x,
            curses.color_pair(2)) 
Example #21
Source File: cryptop.py    From cryptop with MIT License 5 votes vote down vote up
def str_formatter(coin, val, held):
    '''Prepare the coin strings as per ini length/decimal place values'''
    max_length = CONFIG['theme'].getint('field_length', 13)
    dec_place = CONFIG['theme'].getint('dec_places', 2)
    avg_length = CONFIG['theme'].getint('dec_places', 2) + 10
    held_str = '{:>{},.8f}'.format(float(held), max_length)
    val_str = '{:>{},.{}f}'.format(float(held) * val[0], max_length, dec_place)
    return '  {:<5} {:>{}}  {} {:>{}} {:>{}} {:>{}}'.format(coin,
        locale.currency(val[0], grouping=True)[:max_length], avg_length,
        held_str[:max_length],
        locale.currency(float(held) * val[0], grouping=True)[:max_length], avg_length,
        locale.currency(val[1], grouping=True)[:max_length], avg_length,
        locale.currency(val[2], grouping=True)[:max_length], avg_length) 
Example #22
Source File: test_locale.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out) 
Example #23
Source File: middleware.py    From Flask-Large-Application-Example with MIT License 5 votes vote down vote up
def dollar(value):
    """Formats the float value into two-decimal-points dollar amount.
    From http://flask.pocoo.org/docs/templating/

    Positional arguments:
    value -- the string representation of a float to perform the operation on.

    Returns:
    Dollar formatted string.
    """
    return locale.currency(float(value), grouping=True) 
Example #24
Source File: ta_display.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def display_all_total_pay(val):
    amt = locale.currency(float(val))
    return '%s' % (amt) 
Example #25
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def download_financial(request, post_slug):
    posting = get_object_or_404(TAPosting, slug=post_slug, unit__in=request.units)
    all_offerings = CourseOffering.objects.filter(semester=posting.semester, owner=posting.unit)
    # ignore excluded courses
    excl = set(posting.excluded())
    offerings = [o for o in all_offerings if o.course_id not in excl and posting.ta_count(o) > 0]
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'inline; filename="%s-financials-%s.csv"' % \
                                      (post_slug, datetime.datetime.now().strftime('%Y%m%d'))
    writer = csv.writer(response)
    writer.writerow(['Offering', 'Instructor(s)', 'Enrollment', 'Campus', 'Number of TAs', 'Assigned BU',
                     'Total Amount'])
    for o in offerings:
        writer.writerow([o.name(), o.instructors_str(), '(%s/%s)' % (o.enrl_tot, o.enrl_cap), o.get_campus_display(),
                         posting.ta_count(o), posting.assigned_bu(o), locale.currency(float(posting.total_pay(o)))])
    return response 
Example #26
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def _format_currency(i):
    """used to properly format money"""
    return locale.currency(float(i), grouping=True) 
Example #27
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def download_financials(request, unit_slug, semester,):
    hiring_semester = get_object_or_404(HiringSemester,
                                        semester__name=semester,
                                        unit__in=request.units,
                                        unit__label=unit_slug)
    contracts = TAContract.objects.signed(hiring_semester)
    tacourses = TACourse.objects.filter(contract__in=contracts)
    course_offerings = set()
    for course in tacourses:
        course_offerings.add(course.course)
    offerings = []
    for o in course_offerings:
        courses = tacourses.filter(course=o)
        total_pay = 0
        total_bus = decimal.Decimal(0)
        for c in courses:
            total_pay += c.total
            total_bus += c.total_bu
        total_pay = '%s' % (locale.currency(float(total_pay)))
        total_bus = "%.2f" % total_bus
        tas = courses.count()
        o.total_pay = total_pay
        o.total_bus = total_bus
        o.tas = tas
        offerings.append(o)
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'inline; filename="%s-%s-financials-%s.csv"' % \
                                      (unit_slug, semester, datetime.datetime.now().strftime('%Y%m%d'))
    writer = csv.writer(response)
    writer.writerow(['Offering', 'Instructor(s)', 'Enrollment', 'Campus', 'Number of TAs', 'Assigned BU',
                     'Total Amount'])
    for o in offerings:
        writer.writerow([o.name(), o.instructors_str(), '(%s/%s)' % (o.enrl_tot, o.enrl_cap), o.get_campus_display(),
                         o.tas, o.total_bus, o.total_pay])
    return response 
Example #28
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def view_financial_summary(request, unit_slug, semester,):
    hiring_semester = get_object_or_404(HiringSemester,
                                        semester__name=semester,
                                        unit__in=request.units,
                                        unit__label=unit_slug)
    contracts = TAContract.objects.signed(hiring_semester)
    pay = 0
    bus = 0
    tacourses = TACourse.objects.filter(contract__in=contracts)
    course_offerings = set()
    for course in tacourses:
        pay += course.total
        bus += course.total_bu
        course_offerings.add(course.course)
    pay = locale.currency(float(pay))
    pay = '%s' % (pay)
    offerings = []
    tac = 0
    for o in course_offerings:
        courses = tacourses.filter(course=o)
        total_pay = 0
        total_bus = decimal.Decimal(0)
        for c in courses:
            total_pay += c.total
            total_bus += c.total_bu

        total_pay = '%s' % (locale.currency(float(total_pay)))
        total_bus = "%.2f" % total_bus
        tas = courses.count()
        o.total_pay = total_pay
        o.total_bus = total_bus
        o.tas = tas
        tac += tas
        offerings.append(o)
    info = {'course_total': len(offerings), 'bu_total': bus, 'pay_total': pay, 'ta_count': tac}
    context = {'hiring_semester': hiring_semester, 'info': info, 'offerings': offerings, 'unit_slug': unit_slug,
               'semester': semester}
    return render(request, 'tacontracts/view_financial.html', context) 
Example #29
Source File: currency.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def currency(i):
    try:
        return locale.currency(decimal.Decimal(i), grouping=True)
    except decimal.InvalidOperation:
        return locale.currency(0) 
Example #30
Source File: serve.py    From MonitorDarkly with GNU General Public License v3.0 4 votes vote down vote up
def create_and_serve_pic():

    f = open('amount.txt', 'rb')
    amount = int(f.read())

    gif_name = str(amount) + '.gif'
    if not os.path.isfile(os.path.join(STATIC_PATH, gif_name)):
        # Format number
        locale.setlocale(locale.LC_ALL, '')
        formatted_num = locale.currency(amount, grouping=True) + " USD"

        # Generate pic
        img = Image.new('RGB', (500, 500), (255, 255, 255))
        fnt = ImageFont.truetype(os.path.join(FONT_PATH, 'arialbd.ttf'), 25)
        # get a drawing context
        d = ImageDraw.Draw(img)
        # draw text, half opacity
        d.text((1, 0), formatted_num, font=fnt, fill=(51, 51, 51))
        # Crop to text
        (txt_width, txt_height) = d.textsize(formatted_num, font=fnt)
        print txt_height, txt_width
        # if txt_width % 2 == 0
        img = img.crop((0, 0, 300, 26))
        # else:
            # img = img.crop((0, 0, txt_width+1, 26))

        # print "width, height" + str(width) + ", " + str(height)

        baseheight = OUT_HEIGHT
        hpercent = (baseheight / float(img.size[1]))
        wsize = int((float(img.size[0]) * float(hpercent)))
        img = img.resize((wsize, baseheight), Image.ANTIALIAS)

        f, img_name = mkstemp(suffix='.png')
        os.close(f)
        img.save(img_name)

        # Convert to gif
        build_upload_gif(134, 330, img_name, os.path.join(STATIC_PATH, gif_name),
                         clut_offset=17, sdram_offset=0x1000>>6, tile=1)

    return send_from_directory(STATIC_PATH, gif_name)