Python源码示例:locale.currency()
示例1
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
示例2
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')
示例3
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
示例4
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)
示例5
def currency(i):
try:
return locale.currency(decimal.Decimal(i), grouping=True)
except decimal.InvalidOperation:
return locale.currency(0)
示例6
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)
示例7
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
示例8
def _format_currency(i):
"""used to properly format money"""
return locale.currency(float(i), grouping=True)
示例9
def display_all_total_pay(val):
amt = locale.currency(float(val))
return '%s' % (amt)
示例10
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)
示例11
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
示例12
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)
示例13
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))
示例14
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
示例15
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
示例16
def test_currency_us():
assert locale.currency(10.5) == "$10.50"
示例17
def test_currency_br():
assert locale.currency(10.5) == "R$ 10,50"
示例18
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
示例19
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
示例20
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)
示例21
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
示例22
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
示例23
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
示例24
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']
示例25
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
示例26
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()
示例27
def currency_symbol_default(**kwargs):
"""Returns the currency symbol for the current locale."""
return str(locale.localeconv()['currency_symbol'])
示例28
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)
示例29
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
示例30
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)