Python locale 模块,currency() 实例源码

我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用locale.currency()

项目:cryptop    作者:huwwp    | 项目源码 | 文件源码
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 [(data_raw[c][curr]['PRICE'],
                data_raw[c][curr]['HIGH24HOUR'],
                data_raw[c][curr]['LOW24HOUR']) for c in coin.split(',') if c in data_raw.keys()]
    except:
        sys.exit('Could not parse data')
项目:Mac-Python-3.X    作者:L1nwatch    | 项目源码 | 文件源码
def main():
    # ???????????????????,???????????????.??????????
    # ????????UK????????.
    print(loc.setlocale(loc.LC_ALL, ""))
    # print(loc.currency(350)) # ??????
    print(time.strftime("%x %X", time.localtime()))

    # ?????????????????????????????.
    print("{:n}".format(3.14159))
    print("{:n}".format(42))

    # locale.strcoll()?????????????,?????????????????????.
    # ??????????"?"??,?????1,?????-1,????????,???0
    print(loc.strcoll("Spanish", "Inquisition"))
    print(loc.strcoll("Inquisition", "Spanish"))
    print(loc.strcoll("Spanish", "Spanish"))

    # local???????,???????????????:atoi()?atof()?str()?format()?format_string()
项目:Tktr    作者:Intuity    | 项目源码 | 文件源码
def format_price(self, price, symbol=True):
        try:
            locale.setlocale(locale.LC_ALL, "en_GB")
            pricetext = None
            if symbol:
                pricetext = locale.currency((price/100.0)).replace("\xa3","£")
            else:
                pricetext = locale.currency((price/100.0)).replace("\xa3","")
            # Strip all non-ascii characters
            pricetext = "".join(i for i in pricetext if ord(i)<128)
            return pricetext
        except Exception:
            return "-"
项目:Tktr    作者:Intuity    | 项目源码 | 文件源码
def format_price(self, price, symbol=True):
        locale.setlocale(locale.LC_ALL, "en_GB")
        pricetext = None
        if symbol:
            pricetext = locale.currency((price/100.0))
        else:
            pricetext = locale.currency((price/100.0)).replace("\xa3","")
        # Return the price formatted
        decoded = None
        try:
            decoded = pricetext.decode("utf-8")
        except Exception:
            decoded = pricetext.decode("latin-1")
        return decoded
项目:cryptop    作者:huwwp    | 项目源码 | 文件源码
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)
项目:cryptop    作者:huwwp    | 项目源码 | 文件源码
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))
项目:simbuto    作者:nobodyinperson    | 项目源码 | 文件源码
def format_amount_entry(self, entry):
        amount_str = entry.get_text()
        wrongstr = _("This is not a valid amount!")
        try:
            to_float = locale.atof(amount_str)
            formatted_str = locale.currency(to_float,
                grouping=True,symbol=False)
            entry.set_icon_from_stock(Gtk.EntryIconPosition.PRIMARY,None)
            entry.set_text(formatted_str)
            entry.set_tooltip_text(_("Your current total assets"))
        except ValueError:
            entry.set_icon_from_stock(Gtk.EntryIconPosition.PRIMARY,
                Gtk.STOCK_STOP)
            entry.set_icon_tooltip_text(Gtk.EntryIconPosition.PRIMARY,wrongstr)
            entry.set_tooltip_text(wrongstr)
项目:mensa-tracker    作者:annyanich    | 项目源码 | 文件源码
def menu_entry_to_text(entry):
    return ("{date_valid}\n"
            "{mensa}\n"
            "{category}\n"
            "{description}\n"
            "{price}").format(
        description=entry.description.replace("\n", " "),
        mensa=entry.mensa,
        category=entry.category,
        date_valid=entry.date_valid.strftime("%A, %d.%m.%Y"),
        price=currency(entry.price/100)
    )
项目:mensa-tracker    作者:annyanich    | 项目源码 | 文件源码
def __repr__(self):
        return '<MenuEntry scraped: {0} valid: {1} Mensa: {2} Category: {3} ' \
               'Description: {4} Allergens: {5} ' \
               'Price: {6}'.format(self.time_scraped,
                                   self.date_valid,
                                   self.mensa,
                                   self.category,
                                   self.description,
                                   self.allergens,
                                   locale.currency(self.price/100))
项目:mensa-tracker    作者:annyanich    | 项目源码 | 文件源码
def to_pretty_text(self):
        return ("{date_valid}\n"
                "{mensa}: {category}\n"
                "{description}\n"
                "Allergens: {allergens}\n"
                "{price}\n").format(
            description=self.description.replace("\n", " "),
            mensa=self.mensa,
            category=self.category,
            date_valid=self.date_valid.strftime("%A, %d.%m.%Y"),
            allergens=self.allergens,
            price=locale.currency(self.price/100)
        )
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out)
项目:beg-django-e-commerce    作者:Apress    | 项目源码 | 文件源码
def currency(value):
    try:
        locale.setlocale(locale.LC_ALL,'en_US.UTF-8')
    except:
        locale.setlocale(locale.LC_ALL,'')
    loc = locale.localeconv()
    return locale.currency(value, loc['currency_symbol'], grouping=True)

# this can be used if you're having trouble configuring the proper locale 
# for your operating system
#@register.filter(name='currency')
#def currency(value):
#    return '$' + str(value)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out)
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out)
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out)
项目:roulette    作者:gabfl    | 项目源码 | 文件源码
def amountToCurrency(amount):
    """
        Shows an amount in the user currency locale or default to `$`
    """

    try:
        return locale.currency(amount, grouping=True)
    except ValueError:  # If the locale does not support currency formatting
        return '$' + str(round(amount, 2))
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def _test_currency(self, value, out, **format_opts):
        self.assertEqual(locale.currency(value, **format_opts), out)
项目:sopel    作者:senilio    | 项目源码 | 文件源码
def getOutput(res):
    if res['changePercent'] < 0:
        change = '{0:n}%'.format(res['changePercent'])
        try:
            change = formatting.color(change, formatting.colors.RED)
        except:
            pass
    elif res['changePercent'] > 0:
        change = '{0:+n}%'.format(res['changePercent'])
        try:
            change = formatting.color(change, formatting.colors.GREEN)
        except:
            pass
    else:
        change = "0.00%"

    msg = u'{0} ({1}): {2} {3} ({4}). '.format(res['orderBookName'], res['ticker'], locale.currency(res['lastPrice'], symbol=False), res['orderBookCurrency'], change)
    msg += u'Day range: {0}-{1}. '.format(locale.currency(res['lowestPrice'], symbol=False), locale.currency(res['highestPrice'], symbol=False))
    msg += u'Day volume: {0:n}. '.format(res['totalVolumeTraded'])
    if res['totalValueTraded']:
        msg += u'Day revenue: {0:n} {1}. '.format(res['totalValueTraded'], res['orderBookCurrency'])
    if res['networth']:
        msg += u'Net worth: {0} MSEK. '.format(res['networth'])
    if res['peTal'] != '-':
        msg += u'P/E: {0}. '.format(res['peTal'])
    msg += u'Shareholders: {0:n}. (Updated: {1})'.format(res['numOwners'], res['lastUpdate'])
    return msg
项目:sopel    作者:senilio    | 项目源码 | 文件源码
def getOutputFund(res):
    msg = u'{0}: {1} {2}. '.format(res['orderBookName'], locale.currency(res['lastPrice'], symbol=False), res['orderBookCurrency'])
    msg += u'1W: {0}. '.format(percentageColor(res['changePercentWeek']), symbol=False)
    msg += u'1M: {0}. '.format(percentageColor(res['changePercentMonth']), symbol=False)
    msg += u'6M: {0}. '.format(percentageColor(res['changePercentSixMonths']), symbol=False)
    msg += u'1Y: {0}. '.format(percentageColor(res['changePercentOneYear']), symbol=False)
    msg += u'3Y: {0}. '.format(percentageColor(res['changePercentThreeYears']), symbol=False)
    msg += u'5Y: {0}. '.format(percentageColor(res['changePercentFiveYears']), symbol=False)
    msg += u'10Y: {0}. '.format(percentageColor(res['changePercentTenYears']), symbol=False)
    if res['ppm'] != '-':    msg += u'PPM: {0}. '.format(res['ppm'], symbol=False)
    msg += u'Started: {0}. '.format(res['fundStarted'], symbol=False)
    if res['rating'] != '-': msg += u'Rating: {0}. '.format(res['rating'], symbol=False)
    msg += u'Last update: {0}. '.format(res['updated'], symbol=False)
    return msg
项目:flask_jsondash    作者:christabor    | 项目源码 | 文件源码
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)
项目:lego-collection-value    作者:derekbrameyer    | 项目源码 | 文件源码
def get_sets_value(is_collection, brickset_username, brickset_api_key, want_price_as_new, bricklink_consumer_key, bricklink_consumer_secret, bricklink_access_token, bricklink_access_token_secret):
    # Get value of collection
    sets = get_brickset_sets(brickset_username, brickset_api_key, is_collection)

    sets = get_bricklink_sets(sets,
                       want_price_as_new,
                       bricklink_consumer_key,
                       bricklink_consumer_secret,
                       bricklink_access_token,
                       bricklink_access_token_secret)

    min_value = 0
    max_value = 0
    avg_value = 0
    qty_avg_value = 0
    mvs = sets[0]
    success_count = 0

    for s in sets:
        try:
            #print_price_info(s)
            min_value += round_decimal(s.min_price)
            max_value += round_decimal(s.max_price)
            avg_value += round_decimal(s.avg_price)
            qty_avg_value += round_decimal(s.qty_avg_price)
            temp_max_price = None
            try:
                temp_max_price = mvs.max_price
            except AttributeError as e:
                temp_max_price = None
                mvs = s
            if temp_max_price is not None:
                if round_decimal(s.max_price) > round_decimal(mvs.max_price):
                    mvs = s
            success_count += 1
        except AttributeError as e:
            #print 'Error processing set: ' + str(s.number) + "-" + str(s.numberVariant)
            continue

    locale.setlocale(locale.LC_ALL, '')

    print '\n'
    print 'We were able to process ' + str(success_count) + '/' + str(len(sets)) + (' of the sets you %s!' % ('own' if is_collection else 'want'))
    print 'The minimum value of %s is: ' % ('your collection' if is_collection else 'the sets you want') + locale.currency(round_decimal(min_value), grouping=True)
    print 'The maximum value of %s is: ' % ('your collection' if is_collection else 'the sets you want') + locale.currency(round_decimal(max_value), grouping=True)
    print 'The total average value of %s is: ' % ('your collection' if is_collection else 'the sets you want') + locale.currency(round_decimal(avg_value), grouping=True)
    print 'The total quantity average value of %s is: ' % ('your collection' if is_collection else 'the sets you want') + locale.currency(round_decimal(qty_avg_value),
                                                                                 grouping=True)
    try:
        print ('The most valuable set you %s is: ' % ('own' if is_collection else 'want')) + str(mvs.number) + "-" + str(mvs.numberVariant) + " with a value of " + str(locale.currency(round_decimal(mvs.max_price), grouping=True))
    except AttributeError as e:
        pass
项目:MonitorDarkly    作者:RedBalloonShenanigans    | 项目源码 | 文件源码
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)