示例#1
0
    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))
示例#2
0
def test_format_percent():
    assert numbers.format_percent(0.34, locale='en_US') == '34%'
    assert numbers.format_percent(25.1234, locale='en_US') == '2,512%'
    assert (numbers.format_percent(25.1234, locale='sv_SE')
            == '2\xa0512\xa0%')
    assert (numbers.format_percent(25.1234, '#,##0\u2030', locale='en_US')
            == '25,123\u2030')
示例#3
0
def test_format_percent():
    assert numbers.format_percent(0.34, locale='en_US') == u'34%'
    assert numbers.format_percent(25.1234, locale='en_US') == u'2,512%'
    assert (numbers.format_percent(25.1234,
                                   locale='sv_SE') == u'2\xa0512\xa0%')
    assert (numbers.format_percent(25.1234, u'#,##0\u2030',
                                   locale='en_US') == u'25,123\u2030')
示例#4
0
def percent(value, ndigits=3):
    locale = get_current_babel_locale()
    if not ndigits:
        return format_percent(value, locale=locale)
    else:
        format = locale.percent_formats.get(None)
        new_fmt = format.pattern.replace("0", "0." + (ndigits * "#"))
        return format_percent(value, format=new_fmt, locale=locale)
示例#5
0
def percent(value, ndigits=3):
    locale = get_current_babel_locale()
    if not ndigits:
        return format_percent(value, locale=locale)
    else:
        format = locale.percent_formats.get(None)
        new_fmt = format.pattern.replace("0", "0." + (ndigits * "#"))
        return format_percent(value, format=new_fmt, locale=locale)
示例#6
0
def calculate_subproject_amounts(subproject_id):
    subproject = Subproject.query.get(subproject_id)

    # Calculate amounts awarded
    subproject_awarded = 0
    if len(list(subproject.payments)) > 0:
        for payment in subproject.payments:
            if payment.amount_value > 0:
                subproject_awarded += payment.amount_value

    amounts = {
        'id': subproject.id,
        'awarded': subproject_awarded,
        'awarded_str': format_currency(subproject_awarded),
        'spent': 0
    }

    # Calculate amounts spent
    subproject_spent = 0
    for payment in subproject.payments:
        if payment.amount_value < 0:
            # If there is a project IBAN then only add payments
            # if they don't go to the project IBAN to make sure
            # that they aren't counted double
            if subproject.project.iban:
                if payment.counterparty_alias_value != subproject.project.iban:
                    amounts['spent'] += abs(payment.amount_value)
            # If there is no project IBAN simply add all
            # outgoing/negative payments
            else:
                amounts['spent'] += abs(payment.amount_value)

    # Calculate percentage spent
    if amounts['awarded'] == 0:
        amounts['percentage_spent_str'] = (format_percent(0))
    else:
        amounts['percentage_spent_str'] = (format_percent(amounts['spent'] /
                                                          amounts['awarded']))
        if subproject.budget:
            amounts['percentage_spent_str'] = (format_percent(
                amounts['spent'] / subproject.budget))

    amounts['spent_str'] = format_currency(amounts['spent'])

    amounts['left_str'] = format_currency(
        round(amounts['awarded']) - round(amounts['spent']))
    if subproject.budget:
        amounts['left_str'] = format_currency(
            round(subproject.budget) - round(amounts['spent']))

    return amounts
示例#7
0
文件: charts.py 项目: gurch101/shuup
    def add_data(self, name, data, chart_type):
        """
        Add data to this chart
        :param name: the name of the dataset
        :type name: str
        :param data: the list of data
        :type data: list[int|float|Decimal]
        :param chart_type: the chart type - tells how data should be rendered.
            This data type must be available in the `supported_chart_type` attribute of this instance
        :type chart_type: ChartType
        """
        assert chart_type in self.supported_chart_types
        formatted_data = []

        # format value for each data point
        if self.data_type == ChartDataType.CURRENCY:
            for value in data:
                formatted_data.append(format_money(Money(value, currency=self.currency).as_rounded()))

        elif self.data_type == ChartDataType.PERCENT:
            for value in data:
                formatted_data.append(format_percent(value, locale=self.locale))

        # self.data_type == ChartDataType.NUMBER
        else:
            for value in data:
                formatted_data.append(format_decimal(value, locale=self.locale))

        self.datasets.append({"type": chart_type, "label": name, "data": data, "formatted_data": formatted_data})
示例#8
0
 def asString(self, objValue, objType):
     '''
     @see: Converter.asString
     '''
     assert isinstance(objType, Type), 'Invalid object type %s' % objType
     if isinstance(objType, TypeModel):  # If type model is provided we consider the model property type
         assert isinstance(objType, TypeModel)
         container = objType.container
         assert isinstance(container, Model)
         objType = container.properties[container.propertyId]
     if objType.isOf(str):
         return objValue
     if objType.isOf(bool):
         return str(objValue)
     if objType.isOf(Percentage):
         return bn.format_percent(objValue, self.formats.get(Percentage, None), self.locale)
     if objType.isOf(Number):
         return bn.format_decimal(objValue, self.formats.get(Number, None), self.locale)
     if objType.isOf(Date):
         return bd.format_date(objValue, self.formats.get(Date, None), self.locale)
     if objType.isOf(Time):
         return bd.format_time(objValue, self.formats.get(Time, None), self.locale)
     if objType.isOf(DateTime):
         return bd.format_datetime(objValue, self.formats.get(DateTime, None), None, self.locale)
     raise TypeError('Invalid object type %s for Babel converter' % objType)
示例#9
0
    def format_percent(self, number, format=None):
        """Returns formatted percent value for the current locale. Example::

            >>> format_percent(0.34, locale='en_US')
            u'34%'
            >>> format_percent(25.1234, locale='en_US')
            u'2,512%'
            >>> format_percent(25.1234, locale='sv_SE')
            u'2\\xa0512\\xa0%'

        The format pattern can also be specified explicitly::

            >>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
            u'25,123\u2030'

        :param number:
            The percent number to format
        :param format:
            Notation format.
        :returns:
            The formatted percent number.
        """
        return numbers.format_percent(number,
                                      format=format,
                                      locale=self.locale)
示例#10
0
    def add_data(self, name, data, chart_type):
        """
        Add data to this chart
        :param name: the name of the dataset
        :type name: str
        :param data: the list of data
        :type data: list[int|float|Decimal]
        :param chart_type: the chart type - tells how data should be rendered.
            This data type must be available in the `supported_chart_type` attribute of this instance
        :type chart_type: ChartType
        """
        assert chart_type in self.supported_chart_types
        formatted_data = []

        # format value for each data point
        if self.data_type == ChartDataType.CURRENCY:
            for value in data:
                formatted_data.append(format_money(Money(value, currency=self.currency).as_rounded()))

        elif self.data_type == ChartDataType.PERCENT:
            for value in data:
                formatted_data.append(format_percent(value, locale=self.locale))

        # self.data_type == ChartDataType.NUMBER
        else:
            for value in data:
                formatted_data.append(format_decimal(value, locale=self.locale))

        self.datasets.append({"type": chart_type, "label": name, "data": data, "formatted_data": formatted_data})
示例#11
0
def percentage(value):
    if value or value == 0:
        kwargs = {
            'locale': to_locale(get_language()),
            'format': "#,##0.00 %",
        }
        return format_percent(value, **kwargs)
示例#12
0
def test_smoke_numbers(locale):
    locale = Locale.parse(locale)
    for number in NUMBERS:
        assert numbers.format_decimal(number, locale=locale)
        assert numbers.format_currency(number, "EUR", locale=locale)
        assert numbers.format_scientific(number, locale=locale)
        assert numbers.format_percent(number / 100, locale=locale)
示例#13
0
文件: number.py 项目: ppcult/edmunds
 def percent(self, value):
     """
     Format percent
     :param value:   The value to format
     :return:        The formatted value
     """
     return format_percent(value, locale=self._locale)
示例#14
0
def percentage(value):
    if value or value == 0:
        kwargs = {
            'locale': to_locale(get_language()),
            'format': "#,##0.00 %",
        }
        return format_percent(value, **kwargs)
def format_percent(number, format=None, locale=None):
    """Returns formatted percent value for a specific locale.

    .. code-block:: python

       >>> format_percent(0.34, locale='en_US')
       u'34%'
       >>> format_percent(25.1234, locale='en_US')
       u'2,512%'
       >>> format_percent(25.1234, locale='sv_SE')
       u'2\\xa0512\\xa0%'

    The format pattern can also be specified explicitly:

    .. code-block:: python

       >>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
       u'25,123\u2030'

    :param number:
        The percent number to format
    :param format:
        Notation format.
    :param locale:
        A locale code. If not set, uses the currently loaded locale.
    :returns:
        The formatted percent number.
    """
    locale = locale or get_locale()
    return numbers.format_percent(number, format=format, locale=locale)
示例#16
0
 def asString(self, objValue, objType):
     '''
     @see: Converter.asString
     '''
     assert isinstance(objType, Type), 'Invalid object type %s' % objType
     if isinstance(objType, TypeModel): # If type model is provided we consider the model property type
         assert isinstance(objType, TypeModel)
         container = objType.container
         assert isinstance(container, Model)
         objType = container.properties[container.propertyId]
     if objType.isOf(str):
         return objValue
     if objType.isOf(bool):
         return str(objValue)
     if objType.isOf(Percentage):
         return bn.format_percent(objValue, self.formats.get(Percentage, None), self.locale)
     if objType.isOf(Number):
         return bn.format_decimal(objValue, self.formats.get(Number, None), self.locale)
     if objType.isOf(Date):
         return bd.format_date(objValue, self.formats.get(Date, None), self.locale)
     if objType.isOf(Time):
         return bd.format_time(objValue, self.formats.get(Time, None), self.locale)
     if objType.isOf(DateTime):
         return bd.format_datetime(objValue, self.formats.get(DateTime, None), None, self.locale)
     raise TypeError('Invalid object type %s for Babel converter' % objType)
示例#17
0
def format_percent(number, format=None, locale=None):
    """Returns formatted percent value for a specific locale.

    .. code-block:: python

       >>> format_percent(0.34, locale='en_US')
       u'34%'
       >>> format_percent(25.1234, locale='en_US')
       u'2,512%'
       >>> format_percent(25.1234, locale='sv_SE')
       u'2\\xa0512\\xa0%'

    The format pattern can also be specified explicitly:

    .. code-block:: python

       >>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
       u'25,123\u2030'

    :param number:
        The percent number to format
    :param format:
        Notation format.
    :param locale:
        A locale code. If not set, uses the currently loaded locale.
    :returns:
        The formatted percent number.
    """
    locale = locale or get_locale()
    return numbers.format_percent(number, format=format, locale=locale)
示例#18
0
    def percent(self, number, format=None):
        """Return a number formatted as percentage for the locale.

        >>> fmt = Format('en_US')
        >>> fmt.percent(0.34)
        u'34%'
        """
        return format_percent(number, format, locale=self.locale)
示例#19
0
    def percent(self, number, format=None):
        """Return a number formatted as percentage for the locale.

        >>> fmt = Format('en_US')
        >>> fmt.percent(0.34)
        u'34%'
        """
        return format_percent(number, format, locale=self.locale)
示例#20
0
    def percent(self, number, format=None):
        """Return a number formatted as percentage for the locale.

        >>> fmt = Format('en_US')
        >>> fmt.percent(0.34) == '34%'
        True

        :see: `babel.numbers.format_percent`
        """
        return format_percent(number, format, locale=self.locale)
示例#21
0
def format_percent(number, format=None):
    """Return formatted percent value for the locale in request

    :param number: the number to format
    :param format: the format to use
    :return: the formatted percent number
    :rtype: unicode
    """
    locale = get_locale()
    return numbers.format_percent(number, format=format, locale=locale)
示例#22
0
 def percent(self, number, format=None):
     """Return a number formatted as percentage for the locale.
     
     >>> fmt = Format('en_US')
     >>> fmt.percent(0.34) == u('34%')
     True
     
     :see: `babel.numbers.format_percent`
     """
     return format_percent(number, format, locale=self.locale)
示例#23
0
def format_percent(number, format=None):
    """Return formatted percent value for the locale in request

    :param number: the number to format
    :param format: the format to use
    :return: the formatted percent number
    :rtype: unicode
    """
    locale = get_locale()
    return numbers.format_percent(number, format=format, locale=locale)
示例#24
0
    def to_html(self, locale_code):
        if self.data_type == 'currency':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><data value="{2}">{3}</data></td>'.format(
                self.sort_order, self.data_type, self.data_value,
                format_currency(self.data_value,
                                currency=self.options['currency'],
                                locale=locale_code))
        elif self.data_type == 'date':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><time datetime="{2}">{3}</time></td>'.format(
                self.sort_order, self.data_type, self.data_value.isoformat(),
                format_date(self.data_value,
                            format=self.options['format'],
                            locale=locale_code))
        elif self.data_type == 'datetime':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><time datetime="{2}">{3}</time></td>'.format(
                self.sort_order, self.data_type, self.data_value.isoformat(),
                format_datetime(self.data_value,
                                format=self.options['format'],
                                locale=locale_code))
        elif self.data_type == 'decimal':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><data value="{2}">{3}</data></td>'.format(
                self.sort_order, self.data_type, self.data_value,
                format_decimal(self.data_value, locale=locale_code))
        elif self.data_type == 'interval':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><data value="{2}">{3}</data></td>'.format(
                self.sort_order, self.data_type, self.data_value,
                format_interval(self.data_value[0],
                                self.data_value[1],
                                locale=locale_code))
        elif self.data_type == 'percent':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><data value="{2}">{3}</data></td>'.format(
                self.sort_order, self.data_type, self.data_value,
                format_percent(self.data_value, locale=locale_code))
        elif self.data_type == 'scientific':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><data value="{2}">{3}</data></td>'.format(
                self.sort_order, self.data_type, self.data_value,
                format_scientific(self.data_value, locale=locale_code))
        elif self.data_type == 'time':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><time datetime="{2}">{3}</time></td>'.format(
                self.sort_order, self.data_type, self.data_value.isoformat(),
                format_time(self.data_value,
                            format=self.options['format'],
                            locale=locale_code))
        elif self.data_type == 'timedelta':
            temp = int(self.data_value.total_seconds())

            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><time datetime="PT{2}H{3}M{4}S">{5}</time></td>'.format(
                self.sort_order, self.data_type, temp % 60, (temp // 60) % 60,
                (temp // 3600),
                format_timedelta(self.data_value,
                                 format=self.options['format'],
                                 locale=locale_code))

        return '<td data-sort-order="{0:0=8X}" class="data-type-{1}">{2}</td>'.format(
            self.sort_order, self.data_type, self.content)
    def get_reportable_header_table(self, reportable):
        is_percentage = reportable.blueprint.unit == IndicatorBlueprint.PERCENTAGE

        calculated_target = format_total_value_to_string(
            reportable.target,
            is_percentage=is_percentage,
            percentage_display_type="ratio"
            if reportable.blueprint.display_type == 'ratio' else None)

        if reportable.blueprint.display_type == 'percentage':
            calculated_baseline = "%.2f" % reportable.calculated_baseline * 100 if reportable.calculated_baseline * 100 != 0.0 else 0.0
        else:
            v = int(reportable.baseline.get(ValueType.VALUE,
                                            0)) if reportable.baseline.get(
                                                ValueType.VALUE, 0) else 0
            d = int(reportable.baseline.get(
                ValueType.DENOMINATOR, 1)) if reportable.baseline.get(
                    ValueType.DENOMINATOR, 1) else 1

            calculated_baseline = format_total_value_to_string(
                {
                    ValueType.VALUE: v,
                    ValueType.DENOMINATOR: d
                },
                is_percentage=is_percentage,
                percentage_display_type="ratio"
                if reportable.blueprint.display_type == 'ratio' else None)

        return [
            [
                HTMLTableHeader(reportable.blueprint.title,
                                colspan=3,
                                klass='section'),
            ],
            [
                HTMLTableHeader('Calculation method'),
                HTMLTableCell(reportable.blueprint.display_type, colspan=2),
            ],
            [
                HTMLTableHeader('Baseline'),
                HTMLTableCell(calculated_baseline, colspan=2),
            ],
            [
                HTMLTableHeader('Target'),
                HTMLTableCell(calculated_target, colspan=2),
            ],
            [
                HTMLTableHeader('Current Progress'),
                HTMLTableCell(format_percent(
                    reportable.progress_percentage / 100, '#%'),
                              colspan=2),
            ],
        ]
示例#26
0
def format_percent(number, format=None, request=None):
    """Return formatted percent value for the locale in request

    :param number: the number to format
    :param format: the format to use
    :param request: the current Request object
    :return: the formatted percent number
    :rtype: str
    """
    return numbers.format_percent(number,
                                  format=format,
                                  locale=get_locale(request))
示例#27
0
    def format_percent(self, number, format=None, locale=None, **kwargs):
        """Return a percent value formatted for the locale in the
        current request.

        :param number: the number to format
        :param format: the format to use as
            `documented by Babel <http://babel.pocoo.org/docs/numbers/#pattern-syntax>`_.
        :param locale: Overwrite the global locale.

        """
        if number in ('', None):
            return ''
        locale = utils.normalize_locale(locale) or self.get_locale()
        return numbers.format_percent(number, format=format, locale=locale, **kwargs)
示例#28
0
    def percent(self, x, *args, **kwargs):
        if x is None:
            return self.na_str

        if self.decimals is None:
            # Show one decimal by default if values is < 1%
            if abs(x) < 0.01:
                x = round(x, 1 + 2)
            else:
                x = round(x, 2)
        else:
            x = round(x, self.decimals + 2)

        return format_percent(x, locale=self.l, decimal_quantization=False)
示例#29
0
    def convert(self, text):
        """Convert percent according to the target locale

           Args:
              text (str): percent text
           Returns:
              (str): converted percent
        """

        percentPattern = r'^(?P<number>[,\.\xa0\d]*\d)(?P<symbol>\s*%)$'
        numberText = str(parse_decimal(text.strip('%'), locale=self.srcLocale))
        srcFloatPrecision = self._floatPrecision(text, self.srcDecimalSymbol)

        try:
            assert '%' in text

            percentText = str(
                parse_decimal(str((Decimal(numberText) / 100).quantize(
                    Decimal(10)**-srcFloatPrecision)),
                              locale=self.srcLocale))

            if percentText:
                res = format_percent(percentText,
                                     locale=self.tgtLocale,
                                     decimal_quantization=False)

                if self.srcDecimalSymbol in text:
                    match = re.search(percentPattern, res)
                    if self.tgtDecimalSymbol not in res:
                        res = match.group(
                            'number') + self.tgtDecimalSymbol + numberText[
                                numberText.index('.') +
                                1:] + match.group('symbol')
                    elif len(
                            match.group('number')
                        [match.group('number').index(self.tgtDecimalSymbol) +
                         1:]) != srcFloatPrecision - 2:
                        res = match.group(
                            'number')[:match.group('number').index(
                                self.tgtDecimalSymbol
                            )] + self.tgtDecimalSymbol + numberText[
                                numberText.index('.') +
                                1:] + match.group('symbol')
            else:
                res = None
        except:
            res = None

        return res
示例#30
0
def format_percent(number, format=None):
    """Return a formatted percent value.

    If you specify just the number, it uses the default format pattern
    for the current locale. The format parameter can be used to force a
    custom pattern. See the `Babel documentation`_ for details on the
    pattern syntax.

    This function is also available in the template context as filter
    named `percentformat`.

    .. _`Babel documentation`: http://babel.edgewall.org/wiki/Documentation/numbers.html#pattern-syntax
    """
    locale = get_locale()
    return numbers.format_percent(number, format=format, locale=locale)
示例#31
0
def format_percent(number, format=None):
    """Return a formatted percent value.

    If you specify just the number, it uses the default format pattern
    for the current locale. The format parameter can be used to force a
    custom pattern. See the `Babel documentation`_ for details on the
    pattern syntax.

    This function is also available in the template context as filter
    named `percentformat`.

    .. _`Babel documentation`: http://babel.edgewall.org/wiki/Documentation/numbers.html#pattern-syntax
    """
    locale = get_locale()
    return numbers.format_percent(number, format=format, locale=locale)
示例#32
0
def add_helpers_to_context(tell_sentry, context, loc, request=None):
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, request, loc, *a, **kw)
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
    def _to_age(delta):
        try:
            return to_age(delta, loc)
        except:
            return to_age(delta, 'en')
    context['to_age'] = _to_age
示例#33
0
    def format_percent(self, number, format=None):
        """Return formatted percent value

        >>> Locale('en', 'US').format_percent(0.34)
        u'34%'
        >>> Locale('en', 'US').format_percent(25.1234)
        u'2,512%'
        >>> Locale('sv', 'SE').format_percent(25.1234)
        u'2\\xa0512\\xa0%'

        The format pattern can also be specified explicitly:

        >>> Locale('en', 'US').format_percent(25.1234, u'#,##0\u2030')
        u'25,123\u2030'
        """
        return numbers.format_percent(number, format, self)
示例#34
0
def add_helpers_to_context(tell_sentry, context, loc, request=None):
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, request, loc, *a, **kw)
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
    def _to_age(delta, **kw):
        try:
            return to_age(delta, loc, **kw)
        except:
            return to_age(delta, 'en', **kw)
    context['to_age'] = _to_age
示例#35
0
def add_helpers_to_context(context, loc):
    context['escape'] = lambda s: s  # to be overriden by renderers
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(context, loc, *a, **kw)
    context['Money'] = Money
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_money(
        *a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['format_datetime'] = lambda *a: format_datetime(*a, locale=loc)
    context['format_date'] = lambda *a: format_date(*a, locale=loc)
    context['get_lang_options'] = lambda *a, **kw: get_lang_options(
        context['request'], loc, *a, **kw)
    context['to_age'] = to_age

    def format_delta(s, *a):
        return format_decimal(s, *a, format='+#,##0.00;-#,##0.00', locale=loc)

    context['format_delta'] = format_delta

    def parse_decimal_or_400(s, *a):
        try:
            return parse_decimal(s, *a, locale=loc)
        except (InvalidOperation, NumberFormatError, ValueError):
            raise InvalidNumber(s)

    context['parse_decimal'] = parse_decimal_or_400

    def to_age_str(o, **kw):
        if not isinstance(o, datetime):
            kw.setdefault('granularity', 'day')
        return format_timedelta(to_age(o), locale=loc, **kw)

    context['to_age_str'] = to_age_str

    def getdoc(name):
        versions = context['website'].docs[name]
        for lang in context['request'].accept_langs:
            doc = versions.get(lang)
            if doc:
                return doc
        return versions['en']

    context['getdoc'] = getdoc
示例#36
0
def inbound(request):
    context = request.context
    loc = context.locale = get_locale_for_request(request)
    context.decimal_symbol = get_decimal_symbol(locale=loc)
    context._ = lambda s, *a, **kw: get_text(request, loc, s, *a, **kw)
    context.ngettext = lambda *a, **kw: n_get_text(request, loc, *a, **kw)
    context.format_number = lambda *a: format_number(*a, locale=loc)
    context.format_decimal = lambda *a: format_decimal(*a, locale=loc)
    context.format_currency = lambda *a: format_currency(*a, locale=loc)
    context.format_percent = lambda *a: format_percent(*a, locale=loc)
    context.parse_decimal = lambda *a: parse_decimal(*a, locale=loc)
    def _to_age(delta):
        try:
            return to_age(delta, loc)
        except:
            return to_age(delta, 'en')
    context.to_age = _to_age
示例#37
0
def add_helpers_to_context(tell_sentry, context, loc):
    context['escape'] = lambda s: s  # to be overriden by renderers
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, context, loc, *a, **kw)
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
    def _to_age(delta, **kw):
        try:
            return to_age(delta, loc, **kw)
        except:
            return to_age(delta, 'en', **kw)
    context['to_age'] = _to_age
示例#38
0
def add_helpers_to_context(tell_sentry, context, loc):
    context['escape'] = lambda s: s  # to be overriden by renderers
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, context, loc, *a, **kw)
    context['Money'] = Money
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_money(*a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['format_datetime'] = lambda *a: format_datetime(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
    context['to_age'] = to_age
    def to_age_str(o, **kw):
        if not isinstance(o, datetime):
            kw.setdefault('granularity', 'day')
        return format_timedelta(to_age(o), locale=loc, **kw)
    context['to_age_str'] = to_age_str
示例#39
0
def add_helpers_to_context(tell_sentry, context, loc):
    context["escape"] = lambda s: s  # to be overriden by renderers
    context["locale"] = loc
    context["decimal_symbol"] = get_decimal_symbol(locale=loc)
    context["_"] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context["ngettext"] = lambda *a, **kw: n_get_text(tell_sentry, context, loc, *a, **kw)
    context["format_number"] = lambda *a: format_number(*a, locale=loc)
    context["format_decimal"] = lambda *a: format_decimal(*a, locale=loc)
    context["format_currency"] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
    context["format_percent"] = lambda *a: format_percent(*a, locale=loc)
    context["parse_decimal"] = lambda *a: parse_decimal(*a, locale=loc)

    def _to_age(delta, **kw):
        try:
            return to_age(delta, loc, **kw)
        except:
            return to_age(delta, "en", **kw)

    context["to_age"] = _to_age
示例#40
0
def add_helpers_to_context(website, request):
    context = request.context
    loc = context["locale"] = get_locale_for_request(request, website)
    context["decimal_symbol"] = get_decimal_symbol(locale=loc)
    context["_"] = lambda s, *a, **kw: get_text(request, loc, s, *a, **kw)
    context["ngettext"] = lambda *a, **kw: n_get_text(website, request, loc, *a, **kw)
    context["format_number"] = lambda *a: format_number(*a, locale=loc)
    context["format_decimal"] = lambda *a: format_decimal(*a, locale=loc)
    context["format_currency"] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
    context["format_percent"] = lambda *a: format_percent(*a, locale=loc)
    context["parse_decimal"] = lambda *a: parse_decimal(*a, locale=loc)

    def _to_age(delta):
        try:
            return to_age(delta, loc)
        except:
            return to_age(delta, "en")

    context["to_age"] = _to_age
示例#41
0
def inbound(request):
    context = request.context
    loc = context.locale = get_locale_for_request(request)
    context.decimal_symbol = get_decimal_symbol(locale=loc)
    context._ = lambda s, *a, **kw: get_text(request, loc, s, *a, **kw)
    context.ngettext = lambda *a, **kw: n_get_text(request, loc, *a, **kw)
    context.format_number = lambda *a: format_number(*a, locale=loc)
    context.format_decimal = lambda *a: format_decimal(*a, locale=loc)
    context.format_currency = lambda *a, **kw: format_currency_with_options(
        *a, locale=loc, **kw)
    context.format_percent = lambda *a: format_percent(*a, locale=loc)
    context.parse_decimal = lambda *a: parse_decimal(*a, locale=loc)

    def _to_age(delta):
        try:
            return to_age(delta, loc)
        except:
            return to_age(delta, 'en')

    context.to_age = _to_age
示例#42
0
def add_helpers_to_context(website, request):
    context = request.context
    loc = context['locale'] = get_locale_for_request(request, website)
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(request, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(website, request, loc, *
                                                      a, **kw)
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_currency_with_options(
        *a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)

    def _to_age(delta):
        try:
            return to_age(delta, loc)
        except:
            return to_age(delta, 'en')

    context['to_age'] = _to_age
示例#43
0
def add_helpers_to_context(tell_sentry, context, loc):
    context['escape'] = lambda s: s  # to be overriden by renderers
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, context, loc, *a, **kw)
    context['Money'] = Money
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_money(*a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['format_datetime'] = lambda *a: format_datetime(*a, locale=loc)
    context['get_lang_options'] = lambda *a, **kw: get_lang_options(context['request'], loc, *a, **kw)
    context['to_age'] = to_age

    def parse_decimal_or_400(s, *a):
        try:
            return parse_decimal(s, *a, locale=loc)
        except (InvalidOperation, NumberFormatError, ValueError):
            raise InvalidNumber(s)

    context['parse_decimal'] = parse_decimal_or_400

    def to_age_str(o, **kw):
        if not isinstance(o, datetime):
            kw.setdefault('granularity', 'day')
        return format_timedelta(to_age(o), locale=loc, **kw)

    context['to_age_str'] = to_age_str

    def getdoc(name):
        versions = context['website'].docs[name]
        for lang in context['request'].accept_langs:
            doc = versions.get(lang)
            if doc:
                return doc
        return versions['en']

    context['getdoc'] = getdoc
示例#44
0
def format_percent(number, format=None):
    """Return formatted percent value for a specific locale.

    >>> format_percent(0.34, locale='en_US')
    u'34%'
    >>> format_percent(25.1234, locale='en_US')
    u'2,512%'
    >>> format_percent(25.1234, locale='sv_SE')
    u'2\\xa0512\\xa0%'

    The format pattern can also be specified explicitly:

    >>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
    u'25,123\u2030'

    :param number:
        The percent number to format
    :param format:
    :return:
        The formatted percent number
    """
    return numbers.format_percent(number, format=format, locale=local.locale)
示例#45
0
def test_bar_chart_percent():
    labels = ["One", "Two", "Three"]
    locale = "pt_br"
    chart = BarChart("ma biultiful xart %", labels, data_type=ChartDataType.PERCENT, locale=locale)

    dataset1 = OrderedDict({"type": ChartType.BAR, "label": "some bars #1", "data": [0.1, 0.2, 0.3]})
    dataset2 = OrderedDict({"type": ChartType.BAR, "label": "some bars #2", "data": [0.45, 0.55, .999]})
    datasets = [dataset1, dataset2]

    chart.add_data(dataset1["label"], dataset1["data"], dataset1["type"])
    chart.add_data(dataset2["label"], dataset2["data"], dataset2["type"])

    chart_config = chart.get_config()
    assert chart_config["type"] == ChartType.BAR
    assert chart_config["data"]["labels"] == labels

    for i in range(len(chart_config["data"]["datasets"])):
        for j in range(len(chart_config["data"]["datasets"][i]["data"])):
            assert chart_config["data"]["datasets"][i]["data"][j] == datasets[i]["data"][j]

            formatted_data = chart_config["data"]["datasets"][i]["formatted_data"][j]
            assert formatted_data == format_percent(datasets[i]["data"][j], locale=locale)
示例#46
0
def test_bar_chart_percent():
    labels = ["One", "Two", "Three"]
    locale = "pt_br"
    chart = BarChart("ma biultiful xart %", labels, data_type=ChartDataType.PERCENT, locale=locale)

    dataset1 = OrderedDict({"type": ChartType.BAR, "label": "some bars #1", "data": [0.1, 0.2, 0.3]})
    dataset2 = OrderedDict({"type": ChartType.BAR, "label": "some bars #2", "data": [0.45, 0.55, .999]})
    datasets = [dataset1, dataset2]

    chart.add_data(dataset1["label"], dataset1["data"], dataset1["type"])
    chart.add_data(dataset2["label"], dataset2["data"], dataset2["type"])

    chart_config = chart.get_config()
    assert chart_config["type"] == ChartType.BAR
    assert chart_config["data"]["labels"] == labels

    for i in range(len(chart_config["data"]["datasets"])):
        for j in range(len(chart_config["data"]["datasets"][i]["data"])):
            assert chart_config["data"]["datasets"][i]["data"][j] == datasets[i]["data"][j]

            formatted_data = chart_config["data"]["datasets"][i]["formatted_data"][j]
            assert formatted_data == format_percent(datasets[i]["data"][j], locale=locale)
示例#47
0
def add_helpers_to_context(tell_sentry, context, loc):
    context['escape'] = lambda s: s  # to be overriden by renderers
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, context,
                                                      loc, *a, **kw)
    context['Money'] = Money
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_money(
        *a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['format_datetime'] = lambda *a: format_datetime(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
    context['to_age'] = to_age

    def to_age_str(o, **kw):
        if not isinstance(o, datetime):
            kw.setdefault('granularity', 'day')
        return format_timedelta(to_age(o), locale=loc, **kw)

    context['to_age_str'] = to_age_str
示例#48
0
    def format_percent(self, number, format=None):
        """Returns formatted percent value for the current locale. Example::

            >>> format_percent(0.34, locale='en_US')
            u'34%'
            >>> format_percent(25.1234, locale='en_US')
            u'2,512%'
            >>> format_percent(25.1234, locale='sv_SE')
            u'2\\xa0512\\xa0%'

        The format pattern can also be specified explicitly::

            >>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
            u'25,123\u2030'

        :param number:
            The percent number to format
        :param format:
            Notation format.
        :returns:
            The formatted percent number.
        """
        return numbers.format_percent(number, format=format,
                                      locale=self.locale)
示例#49
0
def bp_percentfmt(value, locale='en'):
    return format_percent(value, locale)
示例#50
0
def test_format_percent_precision(input_value, expected_value):
    # Test precision conservation.
    assert numbers.format_percent(
        decimal.Decimal(input_value), locale='en_US', decimal_quantization=False) == expected_value
示例#51
0
    def percent_str(self):
        percent = self.percent / 100

        # TODO: This forces a locale of GB
        return format_percent(percent, "#,##0.##%", locale="en_GB")
示例#52
0
def percentfmt(percent):
    return numbers.format_percent(percent, locale=get_locale())
示例#53
0
def test_format_percent_precision(input_value, expected_value):
    # Test precision conservation.
    assert numbers.format_percent(decimal.Decimal(input_value),
                                  locale='en_US',
                                  decimal_quantization=False) == expected_value
示例#54
0
def test_format_percent_quantization():
    # Test all locales.
    for locale_code in localedata.locale_identifiers():
        assert numbers.format_percent(
            '0.9999999999', locale=locale_code, decimal_quantization=False).find('99999999') > -1
示例#55
0
ids = [x for x in locale_identifiers() if "_" in x]
locales = sorted(ids)

mlines = {}
mids = defaultdict(list)
mlos = {}
storage = io.StringIO()

for lo in locales:
    storage.seek(0)
    storage.truncate()

    n1 = format_decimal(3.1415, locale=lo, decimal_quantization=False)
    n2 = format_number(199_000, locale=lo)
    n3 = format_percent(0.7777, locale=lo)

    print('\t', n1, file=storage)  # 12,345
    print('\t', n2, file=storage)  # 5.679
    print('\t', n3, file=storage)  # 78%

    lines = storage.getvalue()
    key = md5(lines)
    mlines[key] = lines
    mids[key].append(lo)
    mlos[lo] = key

for lo in locales:
    key = mlos[lo]
    lines = mlines.get(key, "")
    if lines:
示例#56
0
 def format_percent(self, *a):
     return format_percent(*a, locale=self)
示例#57
0
 def format_percent(self, *a):
     return format_percent(*a, locale=self)
示例#58
0
def test_format_percent_quantization():
    # Test all locales.
    for locale_code in localedata.locale_identifiers():
        assert numbers.format_percent(
            '0.9999999999', locale=locale_code,
            decimal_quantization=False).find('99999999') > -1
示例#59
0
def format_percent(number):
    return numbers.format_percent(Decimal(str(number)), locale=get_locale())