def filesize_number_format(value): if value < 10: return formats.number_format(round(value, 2), 2) elif value < 100: return formats.number_format(round(value, 2), 1) else: return formats.number_format(round(value, 1), 0)
def djmoney_display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE try: if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return _boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(timezone.localtime(value)) elif isinstance(field, models.DateField) or isinstance(field, models.TimeField): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) else: return smart_unicode(value) except: return smart_unicode(value)
def display_for_field(value, field , **kwargs): from xadmin.views.list import EMPTY_CHANGELIST_VALUE from xadmin.fields import ColorField, ImageWithThumbField if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_text(obj) for obj in value.all()]) elif isinstance(field, ColorField): return collor_field(value) elif isinstance(field, ImageWithThumbField): return image_field(value, field, **kwargs) else: return smart_text(value)
def display_for_field(value, field): from xadmin.defs import EMPTY_CHANGELIST_VALUE if field.flatchoices: if hasattr(value,'__iter__'): rets = [ dict(field.flatchoices).get(e, EMPTY_CHANGELIST_VALUE) for e in value] return ','.join(rets) else: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_unicode(obj) for obj in value.all()]) else: return smart_unicode(value)
def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return _boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(timezone.template_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field, models.FileField) and value: return mark_safe('<a href="%s">%s</a>' % ( conditional_escape(value.url), conditional_escape(value), )) else: return smart_text(value)
def display_for_field(value, field): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): decimal_places = field.decimal_places if decimal_places: point_pos = str(value).rfind('.') if point_pos != -1: # not integer removing_trailing_zeros = str(value).rstrip('0') decimal_places = len(removing_trailing_zeros) - point_pos - 1 else: # integer decimal_places = 0 return formats.number_format(value, decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_text(obj) for obj in value.all()]) else: return smart_text(value)
def _label(self, event, item_or_variation, avail, override_price=None): if isinstance(item_or_variation, ItemVariation): variation = item_or_variation item = item_or_variation.item price = variation.price label = variation.value else: item = item_or_variation price = item.default_price label = item.name if override_price: price = override_price if self.price_included: price = TAXED_ZERO else: price = item.tax(price) if not price.gross: n = '{name}'.format( name=label ) elif not price.rate: n = _('{name} (+ {price})').format( name=label, price=money_filter(price.gross, event.currency) ) elif event.settings.display_net_prices: n = _('{name} (+ {price} plus {taxes}% {taxname})').format( name=label, price=money_filter(price.net, event.currency), taxes=number_format(price.rate), taxname=price.name ) else: n = _('{name} (+ {price} incl. {taxes}% {taxname})').format( name=label, price=money_filter(price.gross, event.currency), taxes=number_format(price.rate), taxname=price.name ) if avail[0] < 20: n += ' – {}'.format(_('SOLD OUT')) elif avail[0] < 100: n += ' – {}'.format(_('Currently unavailable')) else: if avail[1] is not None and event.settings.show_quota_left: n += ' – {}'.format(_('%(num)s currently available') % {'num': avail[1]}) if not isinstance(item_or_variation, ItemVariation) and item.picture: n = escape(n) n += '<br>' n += '<a href="{}" class="productpicture" data-title="{}" data-lightbox={}>'.format( item.picture.url, escape(escape(item.name)), item.id ) n += '<img src="{}" alt="{}">'.format( thumb(item.picture, '60x60^'), escape(item.name) ) n += '</a>' n = mark_safe(n) return n
def _command_qiblat(arg, **kwargs): location_name = arg.strip() or 'Jakarta' try: l = Location.objects.get(city__iexact=location_name) except (Location.DoesNotExist, Location.MultipleObjectsReturned): return 'Afwan, ane belum tahu lokasi "%s" ada dimana.' % location_name direction = qibla.direction(l.lat, l.lng) return '🕋 Arah qiblat untuk {} (koordinat {}, {}) adalah {}° dari utara (searah jarum jam).'.format( l.city, number_format(l.lat), number_format(l.lng), number_format(direction, 2))
def timesheet_report_data(mission, start=None, end=None, padding=False): """Prepare data for timesheet report from start to end. Padding align total in the same column""" timesheets = Timesheet.objects.select_related().filter(mission=mission) months = timesheets.dates("working_date", "month") data = [] for month in months: if start and month < start: continue if end and month > end: break days = daysOfMonth(month) next_month = nextMonth(month) padding_length = 31 - len(days) # Padding for month with less than 31 days to align total column # Header data.append([""]) data.append([formats.date_format(month, format="YEAR_MONTH_FORMAT")]) # Days data.append(["", ] + [d.day for d in days]) dayHeader = [_("Consultants")] + [_(d.strftime("%a")) for d in days] if padding: dayHeader.extend([""] * padding_length) dayHeader.append(_("total")) data.append(dayHeader) for consultant in mission.consultants(): total = 0 row = [consultant, ] consultant_timesheets = {} for timesheet in timesheets.filter(consultant_id=consultant.id, working_date__gte=month, working_date__lt=next_month): consultant_timesheets[timesheet.working_date] = timesheet.charge for day in days: try: charge = consultant_timesheets.get(day) if charge: row.append(formats.number_format(to_int_or_round(charge, 2))) total += charge else: row.append("") except Timesheet.DoesNotExist: row.append("") if padding: row.extend([""] * padding_length) row.append(formats.number_format(to_int_or_round(total, 2))) if total > 0: data.append(row) return data
def get_html_producer_qty_stock_invoiced(self): invoiced_qty, taken_from_stock, customer_qty = self.get_producer_qty_stock_invoiced() if invoiced_qty == DECIMAL_ZERO: if taken_from_stock == DECIMAL_ZERO: return EMPTY_STRING else: return mark_safe(_("Stock %(stock)s") % {'stock': number_format(taken_from_stock, 4)}) else: if taken_from_stock == DECIMAL_ZERO: return mark_safe(_("<b>%(qty)s</b>") % {'qty': number_format(invoiced_qty, 4)}) else: return mark_safe(_("<b>%(qty)s</b> + stock %(stock)s") % {'qty': number_format(invoiced_qty, 4), 'stock': number_format(taken_from_stock, 4)})
def number_renderer(value, field): """ Format a number. :param value: The value to process. :type value: float or long :param field: The model field instance :type field: django.db.models.fields.Field :rtype: unicode """ if isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) return formats.number_format(value)
def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE if isinstance(field, models.DateField) or isinstance(field, models.TimeField): return formats.localize(value) elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return _boolean_icon(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) else: return smart_unicode(value)
def float_format(value): rounded_value = round(value, 1) if rounded_value.is_integer(): decimal_pos = 0 else: decimal_pos = 1 return formats.number_format(rounded_value, decimal_pos)
def bwformat(bps): try: bps = float(bps) except (TypeError, ValueError, UnicodeDecodeError): value = ungettext("%(bw)d bps", "%(bw)d bps", 0) % {'bw': 0} return avoid_wrapping(value) filesize_number_format = lambda value: formats.number_format(round(value, 1), -1) K = 1 * 10 ** 3 M = 1 * 10 ** 6 G = 1 * 10 ** 9 T = 1 * 10 ** 12 P = 1 * 10 ** 15 if bps < K: value = ungettext("%(size)d bps", "%(size)d bps", bps) % {'size': bps} elif bps < M: value = ugettext("%s Kbps") % filesize_number_format(bps / K) elif bps < G: value = ugettext("%s Mbps") % filesize_number_format(bps / M) elif bps < T: value = ugettext("%s Gbps") % filesize_number_format(bps / G) elif bps < P: value = ugettext("%s Tbps") % filesize_number_format(bps / T) else: value = ugettext("%s Pbps") % filesize_number_format(bps / P) return avoid_wrapping(value)
def price(value): if float(value) != 0: return "%(price)s%(currency)s" % { 'price': force_text(formats.number_format(value, 2, use_l10n=settings.USE_L10N)), 'currency': getattr(settings, 'CURRENCY', 'USD')} else: return "N/A"
def cur(value, symbol=None): """ affiche le montant evc son symbole monetaire et comme il faut pour les virgules @param symbol: symbole monetaire @type symbol: string """ if symbol is None: symbol = settings.DEVISE_GENERALE if symbol == 'EUR': symbol = "€" pos_inf = 1e200 * 1e200 neg_inf = -1e200 * 1e200 nan = (1e200 * 1e200) / (1e200 * 1e200) special_floats = [str(pos_inf), str(neg_inf), str(nan)] input_val = force_text(value) try: if input_val in special_floats: val_decim = Decimal(0) else: val_decim = Decimal(input_val) # except UnicodeEncodeError: # val_decim = Decimal(0) except InvalidOperation: try: val_decim = Decimal(force_text(float(value))) except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError): val_decim = Decimal(0) if Decimal('0.0000001') > val_decim > Decimal('-0.0000001'): val_decim = 0 return mark_safe("%s %s" % (formats.number_format(val_decim, 2), symbol))
def _add_share_context(context, request, photos): if len(photos) > 0: photo_url = photos[0].thumbnail.url elif context.get('has_tree'): photo_url = settings.STATIC_URL + "img/tree.png" else: photo_url = settings.STATIC_URL + "img/otmLogo126.png" photo_url = request.build_absolute_uri(photo_url) title = _("%(feature)s on %(treemap)s") % { 'feature': context['title'], 'treemap': request.instance.name } if context.get('benefits_total_currency', 0) > 0: description = \ _("This %(feature)s saves %(currency)s%(amount)s per year.") \ % { 'feature': context['title'], 'currency': context['currency_symbol'], 'amount': number_format(context['benefits_total_currency'], decimal_pos=0) } else: description = _("This %(feature)s is mapped on %(treemap)s") % { 'feature': context['title'], 'treemap': request.instance.name } context['share'] = { 'url': request.build_absolute_uri(), 'title': title, 'description': description, 'image': photo_url, }
def cancel_if_unconfirmed(self, permanence): if settings.REPANIER_SETTINGS_CUSTOMER_MUST_CONFIRM_ORDER \ and not self.is_order_confirm_send \ and self.has_purchase: from repanier.email.email_order import export_order_2_1_customer from repanier.models.purchase import PurchaseWoReceiver filename = "{}-{}.xlsx".format( _("Canceled order"), permanence ) export_order_2_1_customer( self.customer, filename, permanence, cancel_order=True ) purchase_qs = PurchaseWoReceiver.objects.filter( customer_invoice_id=self.id, is_box_content=False, ).order_by('?') for a_purchase in purchase_qs.select_related("customer"): create_or_update_one_cart_item( customer=a_purchase.customer, offer_item_id=a_purchase.offer_item_id, q_order=DECIMAL_ZERO, batch_job=True, comment=_("Qty not confirmed : {}").format(number_format(a_purchase.quantity_ordered, 4)) )
def doc4filesizeformat(bytes, kibi=True): """ Formats the value like a 'human-readable' file size (i.e. 13 KiB, 4.1 MiB, 102 bytes, etc). This does almost the same as django.template.defaultfilters.filesizeformat It fixes the International System of Units which is wrong in django.template.defaultfilters.filesizeformat, indeed, KB, MB, GB and TB should be KiB, MiB, GiB and TiB. """ try: bytes = float(bytes) except (TypeError,ValueError,UnicodeDecodeError): return "%d %s" % (0, _('byte(s)')) number_format = lambda value: formats.number_format(round(value, 1), 1) sizes = [_('byte(s)'), _('KB'), _('MB'), _('GB'), _('TB'), _('PB'), _('EB'), _('ZB'), _('YB')] kibisizes = [_('byte(s)'), _('KiB'), _('MiB'), _('GiB'), _('TiB'), _('PiB'), _('EiB'), _('ZiB'), _('YiB')] if kibi is True or str(kibi) == 'True': power = 1024 szes = kibisizes elif kibi is False or str(kibi) == 'False': power = 1000 szes = sizes szes_pointer = 0 while (int(bytes/power) > 0) and (szes_pointer < len(szes)-1): bytes = bytes/power szes_pointer += 1 return "%s %s" % (number_format(bytes), szes[szes_pointer])
def render(self, name, value, attrs=None): if value != '' and value is not None: try: value = formats.number_format(value, 2) except (TypeError, ValueError): pass return super(CurrencyInput, self).render(name, value, attrs)
def _add_share_context(context, request, photos): if len(photos) > 0: photo_url = photos[0].thumbnail.url elif context.get('has_tree'): photo_url = settings.STATIC_URL + "img/tree.png" else: photo_url = settings.STATIC_URL + "img/otmLogo126.png" photo_url = request.build_absolute_uri(photo_url) title = trans("%s on %s") % (context['title'], request.instance.name) if context.get('benefits_total_currency', 0) > 0: description = trans("This %s saves %s%s per year.") % ( context['title'], context['currency_symbol'], number_format(context['benefits_total_currency'], decimal_pos=0) ) else: description = trans("This %s is mapped on %s.") % ( context['title'], request.instance.name, ) context['share'] = { 'url': request.build_absolute_uri(), 'title': title, 'description': description, 'image': photo_url, }
def _add_share_context(context, request, photos): if len(photos) > 0: photo_url = photos[0].thumbnail.url elif context.get("has_tree"): photo_url = settings.STATIC_URL + "img/tree.png" else: photo_url = settings.STATIC_URL + "img/otmLogo126.png" photo_url = request.build_absolute_uri(photo_url) title = _("%(feature)s on %(treemap)s") % {"feature": context["title"], "treemap": request.instance.name} if context.get("benefits_total_currency", 0) > 0: description = _("This %(feature)s saves %(currency)s%(amount)s per year.") % { "feature": context["title"], "currency": context["currency_symbol"], "amount": number_format(context["benefits_total_currency"], decimal_pos=0), } else: description = _("This %(feature)s is mapped on %(treemap)s") % { "feature": context["title"], "treemap": request.instance.name, } url = reverse( "map_feature_detail", kwargs={"instance_url_name": request.instance.url_name, "feature_id": context["feature"].pk}, ) context["share"] = { "url": request.build_absolute_uri(url), "title": title, "description": description, "image": photo_url, }
def default(self, o): # See "Date Time String Format" in the ECMA-262 specification. if isinstance(o, datetime): r = o.isoformat() if o.microsecond: r = r[:23] + r[26:] if r.endswith('+00:00'): r = r[:-6] + 'Z' return r elif isinstance(o, date): return o.isoformat() elif isinstance(o, time): if is_aware(o): raise ValueError("JSON can't represent timezone-aware times.") r = o.isoformat() if o.microsecond: r = r[:12] return r elif isinstance(o, Decimal): if QUICKAPI_DECIMAL_LOCALE: return number_format(o, use_l10n=True, force_grouping=True) else: return force_text(o) elif isinstance(o, (Promise, Exception, UUID)): return force_text(o) elif isinstance(o, GeneratorType): return list(o) else: return super(JSONEncoder, self).default(o)
def sofilesizeformat(bytes): """ Like the django filesizeformat except with decimal file sizes. """ try: bytes = float(bytes) except (TypeError, ValueError, UnicodeDecodeError): return 'o byte' filesize_number_format = lambda value: formats.number_format(round(value, 1), 1) KB = 10 ** 3 MB = 10 ** 6 GB = 10 ** 9 TB = 10 ** 12 PB = 10 ** 15 if bytes < KB: value = "%s bytes" % bytes elif bytes < MB: value = "%s KB" % filesize_number_format(bytes / KB) elif bytes < GB: value = "%s MB" % filesize_number_format(bytes / MB) elif bytes < TB: value = "%s GB" % filesize_number_format(bytes / GB) elif bytes < PB: value = "%s TB" % filesize_number_format(bytes / TB) else: value = "%s PB" % filesize_number_format(bytes / PB) return value
def filesizeformat(bytes, decimals=1): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). Based on django.template.defaultfilters.filesizeformat """ try: bytes = float(bytes) except (TypeError, ValueError, UnicodeDecodeError): raise ValueError filesize_number_format = lambda value: formats.number_format(round(value, decimals), decimals) units_list = sorted(six.iteritems(FILESIZE_UNITS), key=operator.itemgetter(1)) value = unit = None len_unints_list = len(units_list) for i in xrange(1, len_unints_list): if bytes < units_list[i][1]: prev_unit = units_list[i - 1] value = filesize_number_format(bytes / prev_unit[1]) unit = prev_unit[0] break if value is None: value = filesize_number_format(bytes / units_list[-1][1]) unit = units_list[-1][0] return SIZEFIELD_FORMAT.format(value=value, unit=unit)
def filesizeformat(bytes): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes = float(bytes) except (TypeError, ValueError, UnicodeDecodeError): value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} return avoid_wrapping(value) filesize_number_format = lambda value: formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 if bytes < KB: value = ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes} elif bytes < MB: value = ugettext("%s KB") % filesize_number_format(bytes / KB) elif bytes < GB: value = ugettext("%s MB") % filesize_number_format(bytes / MB) elif bytes < TB: value = ugettext("%s GB") % filesize_number_format(bytes / GB) elif bytes < PB: value = ugettext("%s TB") % filesize_number_format(bytes / TB) else: value = ugettext("%s PB") % filesize_number_format(bytes / PB) return avoid_wrapping(value)
def seahub_filesizeformat(bytes): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). """ try: bytes = float(bytes) except (TypeError, ValueError, UnicodeDecodeError): value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0} return avoid_wrapping(value) filesize_number_format = lambda value: formats.number_format(round(value, 1), 1) KB = get_file_size_unit("KB") MB = get_file_size_unit("MB") GB = get_file_size_unit("GB") TB = get_file_size_unit("TB") PB = get_file_size_unit("PB") if bytes < KB: value = ungettext("%(size)d byte", "%(size)d bytes", bytes) % {"size": bytes} elif bytes < MB: value = ugettext("%s KB") % filesize_number_format(bytes / KB) elif bytes < GB: value = ugettext("%s MB") % filesize_number_format(bytes / MB) elif bytes < TB: value = ugettext("%s GB") % filesize_number_format(bytes / GB) elif bytes < PB: value = ugettext("%s TB") % filesize_number_format(bytes / TB) else: value = ugettext("%s PB") % filesize_number_format(bytes / PB) return avoid_wrapping(value)
def clean(self): if any(self.errors): # Don't bother validating the formset unless each form is valid on its own return qty_invoiced = DECIMAL_ZERO values = set() for form in self.forms: if form.cleaned_data and not form.cleaned_data.get('DELETE'): # This is not an empty form or a "to be deleted" form value = form.cleaned_data.get('customer', None) if value is not None: if value in values: raise forms.ValidationError(_('The same customer can not be selected twice.')) else: values.add(value) qty_invoiced += form.cleaned_data.get('quantity_invoiced', DECIMAL_ZERO).quantize(THREE_DECIMALS) if self.instance.manage_replenishment: stock = Decimal(self.data.get("stock", DECIMAL_ZERO)).quantize(THREE_DECIMALS) qty_delivered = Decimal(self.data.get("qty_delivered", DECIMAL_ZERO)).quantize(THREE_DECIMALS) if qty_invoiced > stock + qty_delivered: raise ValidationError( _( 'Total quantity invoiced %(qty_invoiced)s is greather than the sum of the stock and the quantity delivered.') % { 'qty_invoiced': number_format(qty_invoiced, 3) } )
def format_benefits(instance, benefits, basis): currency_symbol = '' if instance.eco_benefits_conversion: currency_symbol = instance.eco_benefits_conversion.currency_symbol # FYI: this mutates the underlying benefit dictionaries for benefit_group in benefits.values(): for key, benefit in benefit_group.iteritems(): if benefit['currency'] is not None: # TODO: Use i18n/l10n to format currency benefit['currency_saved'] = currency_symbol + number_format( benefit['currency'], decimal_pos=0) unit_key = benefit.get('unit-name') if unit_key: _, value = get_display_value( instance, unit_key, key, benefit['value']) benefit['name'] = key benefit['value'] = value benefit['unit'] = get_units(instance, unit_key, key) # Add total and percent to basis rslt = {'benefits': benefits, 'currency_symbol': currency_symbol, 'basis': basis} return rslt
def _format_amount(self, value): from django.utils.formats import number_format # workaround for django not treating decimal_places==0 is implied # as prices always are rounded to their decimal_places, see # utils.price_amount # see https://code.djangoproject.com/ticket/13810 return number_format(value, self.currency.decimal_places or 0)
def to_representation(self, obj): return number_format(obj)
def print_decimal(entity, fval, user, field): # TODO remove 'use_l10n' when settings.USE_L10N == True return number_format(fval, use_l10n=True) if fval is not None else ''
def default(self, obj): if isinstance(obj, AbstractMoney): return number_format(obj) return super(JSONEncoder, self).default(obj)
def fmt(x): return str(formats.number_format(round(x, 1), 1))
def get_whosale_price(self, obj): user = self.context['request'].user whosale_price = obj.get_whosale_price(user) return number_format(whosale_price)
def preco_total_formatado(self): total = 0 for item in models.Item.objects.select_related().filter( carrinho=self.carrinho): total += item.preco_total return number_format(total, 2)
def float_format(value): return formats.number_format(round(value, 1), 0)
def subtotal_formated(self): return u"R$ %s" % number_format(self.subtotal, 2)
def get_commission(self): return u"%s" % number_format(self.commission * 100, 0)
def price_sale_formated(self): return u"R$ %s" % number_format(self.price_sale, 2)
def get_ipi(self): return u"%s" % number_format(self.ipi_sale * 100, 0)
def get_total(self): qs = self.sales_det.filter(sale=self.pk).values_list( 'price_sale', 'quantity') or 0 t = 0 if isinstance(qs, int) else sum(map(lambda q: q[0] * q[1], qs)) return u"R$ %s" % number_format(t, 2)
def get_price(self): return u"R$ %s" % number_format(self.price, 2)
def filesize_number_format(value): return formats.number_format(round(value, decimals), decimals)
def format_number(amount): return formats.number_format(amount, decimal_pos=2, use_l10n=True, force_grouping=True)
def bp_number_format(value): return formats.number_format(round(value, 1), 1)
def floatformat(text, arg=-1): """ Display a float to a specified number of decimal places. If called without an argument, display the floating point number with one decimal place -- but only if there's a decimal place to be displayed: * num1 = 34.23234 * num2 = 34.00000 * num3 = 34.26000 * {{ num1|floatformat }} displays "34.2" * {{ num2|floatformat }} displays "34" * {{ num3|floatformat }} displays "34.3" If arg is positive, always display exactly arg number of decimal places: * {{ num1|floatformat:3 }} displays "34.232" * {{ num2|floatformat:3 }} displays "34.000" * {{ num3|floatformat:3 }} displays "34.260" If arg is negative, display arg number of decimal places -- but only if there are places to be displayed: * {{ num1|floatformat:"-3" }} displays "34.232" * {{ num2|floatformat:"-3" }} displays "34" * {{ num3|floatformat:"-3" }} displays "34.260" If the input float is infinity or NaN, display the string representation of that value. """ try: input_val = repr(text) d = Decimal(input_val) except InvalidOperation: try: d = Decimal(str(float(text))) except (ValueError, InvalidOperation, TypeError): return "" try: p = int(arg) except ValueError: return input_val try: m = int(d) - d except (ValueError, OverflowError, InvalidOperation): return input_val if not m and p < 0: return mark_safe(formats.number_format("%d" % (int(d)), 0)) exp = Decimal(1).scaleb(-abs(p)) # Set the precision high enough to avoid an exception (#15789). tupl = d.as_tuple() units = len(tupl[1]) units += -tupl[2] if m else tupl[2] prec = abs(p) + units + 1 # Avoid conversion to scientific notation by accessing `sign`, `digits`, # and `exponent` from Decimal.as_tuple() directly. sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec)).as_tuple() digits = [str(digit) for digit in reversed(digits)] while len(digits) <= abs(exponent): digits.append("0") digits.insert(-exponent, ".") if sign: digits.append("-") number = "".join(reversed(digits)) return mark_safe(formats.number_format(number, abs(p)))
def sum_str_format(value): zero = 'ноль' ten = ( ('', 'один', 'два', 'три', 'четыре', 'пять', 'шесть', 'семь', 'восемь', 'девять'), ('', 'одна', 'две', 'три', 'четыре', 'пять', 'шесть', 'семь', 'восемь', 'девять'), ) a20 = [ 'десять', 'одиннадцать', 'двенадцать', 'тринадцать', 'четырнадцать', 'пятнадцать', 'шестнадцать', 'семнадцать', 'восемнадцать', 'девятнадцать' ] tens = [ '', '', 'двадцать', 'тридцать', 'сорок', 'пятьдесят', 'шестьдесят', 'семьдесят', 'восемьдесят', 'девяносто' ] hundred = [ '', 'сто', 'двести', 'триста', 'четыреста', 'пятьсот', 'шестьсот', 'семьсот', 'восемьсот', 'девятьсот' ] unit = [ # Units ['копейка', 'копейки', 'копеек', 1], ['рубль', 'рубля', 'рублей', 1], ['тысяча', 'тысячи', 'тысяч', 1], ['миллион', 'миллиона', 'миллионов', 0], ['миллиард', 'милиарда', 'миллиардов', 0], ] value = str(value).replace(' ', '') if '.' in value: rub, kop = ('%3.2f' % float(value)).split('.') elif ',' in value: rub, kop = ('%3.2f' % float(value)).split(',') else: rub = float(value) kop = 0 digits = [] currency = [] def split_by_groups(value: str, count: int): value = str(int(value)) extended_length = len(value) * 1.0 / count extended_value = value.rjust(math.ceil(extended_length) * count, '0') return [extended_value[i: i + count] for i in range(0, len(extended_value), count)] def morph(value, var1, var2, var3): value = abs(int(value)) % 100 if value > 10 and value < 20: return var3 value = value % 10 if value > 1 and value < 5: return var2 if value == 1: return var1 return var3 if int(rub) > 0: groups = split_by_groups(rub, 3) rub_formatted = str(number_format(rub, force_grouping=True)) for id, group in enumerate(groups): i1, i2, i3 = list([int(g) for g in group]) unit_id = len(groups) - id current_unit = unit[unit_id] gender = current_unit[3] if i1 > 0: digits.append(hundred[i1]) if i2 > 1: if i3 != 0: text = tens[i2] + ' ' + ten[gender][i3] else: text = tens[i2] # 20-99 digits.append(text) else: if i2 > 0: text = a20[i3] else: text = ten[gender][i3] # 10-19 | 1-9 digits.append(text) if unit_id > 0: if id == len(groups) - 1: currency.append(morph(group, *current_unit[:3])) elif int(group) > 0: digits.append(morph(group, *current_unit[:3])) currency.append(str(kop)) currency.append(morph(kop, *unit[0][:3])) digits_str = ' '.join(digits).strip() return rub_formatted + ' (' + digits_str.capitalize() + ') ' + ' '.join(currency).strip()
def filesize_number_format(value): return formats.number_format(round(value, 1), 1)
def _label(self, event, item_or_variation, avail, override_price=None, initial=False): if isinstance(item_or_variation, ItemVariation): variation = item_or_variation item = item_or_variation.item price = variation.price label = variation.value else: item = item_or_variation price = item.default_price label = item.name if override_price: price = override_price if self.price_included: price = TAXED_ZERO else: price = item.tax(price) if not price.gross: n = '{name}'.format(name=label) elif not price.rate: n = _('{name} (+ {price})').format(name=label, price=money_filter( price.gross, event.currency)) elif event.settings.display_net_prices: n = _('{name} (+ {price} plus {taxes}% {taxname})').format( name=label, price=money_filter(price.net, event.currency), taxes=number_format(price.rate), taxname=price.name) else: n = _('{name} (+ {price} incl. {taxes}% {taxname})').format( name=label, price=money_filter(price.gross, event.currency), taxes=number_format(price.rate), taxname=price.name) if not initial: if avail[0] < Quota.AVAILABILITY_RESERVED: n += ' – {}'.format(_('SOLD OUT')) elif avail[0] < Quota.AVAILABILITY_OK: n += ' – {}'.format(_('Currently unavailable')) else: if avail[1] is not None and item.do_show_quota_left: n += ' – {}'.format( _('%(num)s currently available') % {'num': avail[1]}) if not isinstance(item_or_variation, ItemVariation) and item.picture: n = escape(n) n += '<br>' n += '<a href="{}" class="productpicture" data-title="{}" data-lightbox={}>'.format( item.picture.url, escape(escape(item.name)), item.id) n += '<img src="{}" alt="{}">'.format( thumb(item.picture, '60x60^'), escape(item.name)) n += '</a>' n = mark_safe(n) return n
def floatformat(text, arg=-1): """ Displays a float to a specified number of decimal places. If called without an argument, it displays the floating point number with one decimal place -- but only if there's a decimal place to be displayed: * num1 = 34.23234 * num2 = 34.00000 * num3 = 34.26000 * {{ num1|floatformat }} displays "34.2" * {{ num2|floatformat }} displays "34" * {{ num3|floatformat }} displays "34.3" If arg is positive, it will always display exactly arg number of decimal places: * {{ num1|floatformat:3 }} displays "34.232" * {{ num2|floatformat:3 }} displays "34.000" * {{ num3|floatformat:3 }} displays "34.260" If arg is negative, it will display arg number of decimal places -- but only if there are places to be displayed: * {{ num1|floatformat:"-3" }} displays "34.232" * {{ num2|floatformat:"-3" }} displays "34" * {{ num3|floatformat:"-3" }} displays "34.260" If the input float is infinity or NaN, the (platform-dependent) string representation of that value will be displayed. """ try: input_val = force_unicode(text) d = Decimal(input_val) except UnicodeEncodeError: return u'' except InvalidOperation: if input_val in special_floats: return input_val try: d = Decimal(force_unicode(float(text))) except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError): return u'' try: p = int(arg) except ValueError: return input_val try: m = int(d) - d except (ValueError, OverflowError, InvalidOperation): return input_val if not m and p < 0: return mark_safe(formats.number_format(u'%d' % (int(d)), 0)) if p == 0: exp = Decimal(1) else: exp = Decimal(u'1.0') / (Decimal(10)**abs(p)) try: # Set the precision high enough to avoid an exception, see #15789. tupl = d.as_tuple() units = len(tupl[1]) - tupl[2] prec = abs(p) + units + 1 # Avoid conversion to scientific notation by accessing `sign`, `digits` # and `exponent` from `Decimal.as_tuple()` directly. sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec)).as_tuple() digits = [unicode(digit) for digit in reversed(digits)] while len(digits) <= abs(exponent): digits.append(u'0') digits.insert(-exponent, u'.') if sign: digits.append(u'-') number = u''.join(reversed(digits)) return mark_safe(formats.number_format(number, abs(p))) except InvalidOperation: return input_val
def get_display(self, qty=0, order_unit=PRODUCT_ORDER_UNIT_PC, unit_price_amount=None, for_customer=True, for_order_select=False, without_price_display=False): magnitude = None display_qty = True if order_unit == PRODUCT_ORDER_UNIT_KG: if qty == DECIMAL_ZERO: unit = EMPTY_STRING elif for_customer and qty < 1: unit = "%s" % (_('gr')) magnitude = 1000 else: unit = "%s" % (_('kg')) elif order_unit == PRODUCT_ORDER_UNIT_LT: if qty == DECIMAL_ZERO: unit = EMPTY_STRING elif for_customer and qty < 1: unit = "%s" % (_('cl')) magnitude = 100 else: unit = "%s" % (_('l')) elif order_unit in [ PRODUCT_ORDER_UNIT_PC_KG, PRODUCT_ORDER_UNIT_PC_PRICE_KG ]: # display_qty = not (order_average_weight == 1 and order_unit == PRODUCT_ORDER_UNIT_PC_PRICE_KG) average_weight = self.order_average_weight if for_customer: average_weight *= qty if order_unit == PRODUCT_ORDER_UNIT_PC_KG and unit_price_amount is not None: unit_price_amount *= self.order_average_weight if average_weight < 1: average_weight_unit = _('gr') average_weight *= 1000 else: average_weight_unit = _('kg') decimal = 3 if average_weight == int(average_weight): decimal = 0 elif average_weight * 10 == int(average_weight * 10): decimal = 1 elif average_weight * 100 == int(average_weight * 100): decimal = 2 tilde = EMPTY_STRING if order_unit == PRODUCT_ORDER_UNIT_PC_KG: tilde = '~' if for_customer: if qty == DECIMAL_ZERO: unit = EMPTY_STRING else: if self.order_average_weight == 1 and order_unit == PRODUCT_ORDER_UNIT_PC_PRICE_KG: unit = "%s%s %s" % ( tilde, number_format(average_weight, decimal), average_weight_unit) else: unit = "%s%s%s" % ( tilde, number_format(average_weight, decimal), average_weight_unit) else: if qty == DECIMAL_ZERO: unit = EMPTY_STRING else: unit = "%s%s%s" % (tilde, number_format(average_weight, decimal), average_weight_unit) elif order_unit == PRODUCT_ORDER_UNIT_PC_PRICE_LT: display_qty = self.order_average_weight != 1 average_weight = self.order_average_weight if for_customer: average_weight *= qty if average_weight < 1: average_weight_unit = _('cl') average_weight *= 100 else: average_weight_unit = _('l') decimal = 3 if average_weight == int(average_weight): decimal = 0 elif average_weight * 10 == int(average_weight * 10): decimal = 1 elif average_weight * 100 == int(average_weight * 100): decimal = 2 if for_customer: if qty == DECIMAL_ZERO: unit = EMPTY_STRING else: if display_qty: unit = "%s%s" % (number_format( average_weight, decimal), average_weight_unit) else: unit = "%s %s" % (number_format( average_weight, decimal), average_weight_unit) else: if qty == DECIMAL_ZERO: unit = EMPTY_STRING else: unit = "%s%s" % (number_format( average_weight, decimal), average_weight_unit) elif order_unit == PRODUCT_ORDER_UNIT_PC_PRICE_PC: display_qty = self.order_average_weight != 1 average_weight = self.order_average_weight if for_customer: average_weight *= qty if qty == DECIMAL_ZERO: unit = EMPTY_STRING else: if average_weight < 2: pc_pcs = _('pc') else: pc_pcs = _('pcs') if display_qty: unit = "%s%s" % (number_format(average_weight, 0), pc_pcs) else: unit = "%s %s" % (number_format(average_weight, 0), pc_pcs) else: if average_weight == DECIMAL_ZERO: unit = EMPTY_STRING elif average_weight < 2: unit = '%s %s' % (number_format(average_weight, 0), _('pc')) else: unit = '%s %s' % (number_format(average_weight, 0), _('pcs')) else: if for_order_select: if qty == DECIMAL_ZERO: unit = EMPTY_STRING elif qty < 2: unit = "%s" % (_('unit')) else: unit = "%s" % (_('units')) else: unit = EMPTY_STRING if unit_price_amount is not None: price_display = " = %s" % RepanierMoney(unit_price_amount * qty) else: price_display = EMPTY_STRING if magnitude is not None: qty *= magnitude decimal = 3 if qty == int(qty): decimal = 0 elif qty * 10 == int(qty * 10): decimal = 1 elif qty * 100 == int(qty * 100): decimal = 2 if for_customer or for_order_select: if unit: if display_qty: qty_display = "%s (%s)" % (number_format(qty, decimal), unit) else: qty_display = "%s" % unit else: qty_display = "%s" % number_format(qty, decimal) else: if unit: qty_display = "(%s)" % unit else: qty_display = EMPTY_STRING if without_price_display: return qty_display else: display = "%s%s" % (qty_display, price_display) return display
'NullBooleanField': _boolean_printer, 'ForeignKey': _fk_printer, 'DateField': lambda field, val, user: date_format(date_from_ISO8601(val), 'DATE_FORMAT') if val else '', 'DateTimeField': lambda field, val, user: date_format( localtime(dt_from_ISO8601(val)), 'DATETIME_FORMAT', ) if val else '', # TODO remove 'use_l10n' when settings.USE_L10N == True 'FloatField': lambda field, val, user: number_format(val, use_l10n=True) if val is not None else '', } class _HistoryLineTypeRegistry: __slots__ = ('_hltypes', ) def __init__(self): self._hltypes = {} def __call__(self, type_id): assert type_id not in self._hltypes, 'ID collision' def _aux(cls): self._hltypes[type_id] = cls
def serialize_decimal(value: Decimal) -> str: return number_format(value)
def __str__(self): value = self.value return number_format(value, use_l10n=True) if value else ''
def floatformat(text, arg=-1): """ Display a float to a specified number of decimal places. If called without an argument, display the floating point number with one decimal place -- but only if there's a decimal place to be displayed: * num1 = 34.23234 * num2 = 34.00000 * num3 = 34.26000 * {{ num1|floatformat }} displays "34.2" * {{ num2|floatformat }} displays "34" * {{ num3|floatformat }} displays "34.3" If arg is positive, always display exactly arg number of decimal places: * {{ num1|floatformat:3 }} displays "34.232" * {{ num2|floatformat:3 }} displays "34.000" * {{ num3|floatformat:3 }} displays "34.260" If arg is negative, display arg number of decimal places -- but only if there are places to be displayed: * {{ num1|floatformat:"-3" }} displays "34.232" * {{ num2|floatformat:"-3" }} displays "34" * {{ num3|floatformat:"-3" }} displays "34.260" If arg has the 'g' suffix, force the result to be grouped by the THOUSAND_SEPARATOR for the active locale. When the active locale is en (English): * {{ 6666.6666|floatformat:"2g" }} displays "6,666.67" * {{ 10000|floatformat:"g" }} displays "10,000" If the input float is infinity or NaN, display the string representation of that value. """ force_grouping = False if isinstance(arg, str) and arg.endswith('g'): force_grouping = True arg = arg[:-1] or -1 try: input_val = repr(text) d = Decimal(input_val) except InvalidOperation: try: d = Decimal(str(float(text))) except (ValueError, InvalidOperation, TypeError): return '' try: p = int(arg) except ValueError: return input_val try: m = int(d) - d except (ValueError, OverflowError, InvalidOperation): return input_val if not m and p < 0: return mark_safe( formats.number_format('%d' % (int(d)), 0, force_grouping=force_grouping), ) exp = Decimal(1).scaleb(-abs(p)) # Set the precision high enough to avoid an exception (#15789). tupl = d.as_tuple() units = len(tupl[1]) units += -tupl[2] if m else tupl[2] prec = abs(p) + units + 1 # Avoid conversion to scientific notation by accessing `sign`, `digits`, # and `exponent` from Decimal.as_tuple() directly. rounded_d = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec)) sign, digits, exponent = rounded_d.as_tuple() digits = [str(digit) for digit in reversed(digits)] while len(digits) <= abs(exponent): digits.append('0') digits.insert(-exponent, '.') if sign and rounded_d: digits.append('-') number = ''.join(reversed(digits)) return mark_safe( formats.number_format(number, abs(p), force_grouping=force_grouping), )
def valor_total_formatado(self): return number_format(self.valor_total, 2)
def valor_frete(self): return number_format(self.frete, 2)
def intcomma(value, instance): if not value: return 0 return number_format(value, force_grouping=True)
def render_value(self, field_name=None): value = super(BaseNumberField, self).render_value(field_name=field_name) if isinstance(value, numbers.Number): value = number_format(value) return value