File: currency.py

package info (click to toggle)
kiwi 1.9.22-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 11,908 kB
  • ctags: 5,549
  • sloc: python: 15,779; ansic: 193; xml: 77; makefile: 57; sh: 17
file content (211 lines) | stat: -rw-r--r-- 6,838 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#
# Kiwi: a Framework and Enhanced Widgets for Python
#
# Copyright (C) 2005-2006 Async Open Source
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
# USA
#
# Author(s): Johan Dahlin <jdahlin@async.com.br>
#

"""Currency and datatype converter"""

import gettext

from kiwi.datatypes import HAVE_DECIMAL, Decimal, InvalidOperation
from kiwi.datatypes import ValidationError, ValueUnset
from kiwi.datatypes import converter, get_localeconv, filter_locale
from kiwi.enums import Alignment

_ = lambda m: gettext.dgettext('kiwi', m)

class currency(Decimal):
    """
    A datatype representing currency, used together with the list and
    the framework
    """
    _converter = converter.get_converter(Decimal)

    def __new__(cls, value):
        """
        Convert value to currency.
        @param value: value to convert
        @type value: string or number
        """
        if isinstance(value, str):
            conv = get_localeconv()
            currency_symbol = conv.get('currency_symbol')
            text = value.strip(currency_symbol)
            # if we cannot convert it using locale information, still try to
            # create
            try:
                text = filter_locale(text, monetary=True)
                value = currency._converter.from_string(text)
            except ValidationError:
                # Decimal does not accept leading and trailing spaces. See
                # bug 1516613
                value = text.strip()

            if value == ValueUnset:
                raise InvalidOperation
        elif HAVE_DECIMAL and isinstance(value, float):
            print ('Warning: losing precision converting float %r to currency'
                   % value)
            value = str(value)
        elif not isinstance(value, (int, long, Decimal)):
            raise TypeError(
                "cannot convert %r of type %s to a currency" % (
                value, type(value)))

        return Decimal.__new__(cls, value)

    def format(self, symbol=True, precision=None):
        value = Decimal(self)

        conv = get_localeconv()

        # Grouping (eg thousand separator) of integer part
        groups = conv.get('mon_grouping', [])[:]
        groups.reverse()
        if groups:
            group = groups.pop()
        else:
            group = 3

        intparts = []

        # We're iterating over every character in the integer part
        # make sure to remove the negative sign, it'll be added later
        intpart = str(int(abs(value)))

        while True:
            if not intpart:
                break

            s = intpart[-group:]
            intparts.insert(0, s)
            intpart = intpart[:-group]
            if not groups:
                continue

            last = groups.pop()
            # if 0 reuse last one, see struct lconv in locale.h
            if last != 0:
                group = last

        # Add the sign, and the list of decmial parts, which now are grouped
        # properly and can be joined by mon_thousand_sep
        if value > 0:
            sign = conv.get('positive_sign', '')
        elif value < 0:
            sign = conv.get('negative_sign', '-')
        else:
            sign = ''
        currency = sign + conv.get('mon_thousands_sep', '.').join(intparts)

        # Only add decimal part if it has one, is this correct?
        if precision is not None or value % 1 != 0:
            # Pythons string formatting can't handle %.127f
            # 127 is the default value from glibc/python
            if precision:
                frac_digits = precision
            else:
                frac_digits = conv.get('frac_digits', 2)
                if frac_digits == 127:
                    frac_digits = 2

            format = '%%.%sf' % frac_digits
            dec_part = (format % value)[-frac_digits:]

            mon_decimal_point = conv.get('mon_decimal_point', '.')
            currency += mon_decimal_point + dec_part

        # If requested include currency symbol
        currency_symbol = conv.get('currency_symbol', '')
        if currency_symbol and symbol:
            if value > 0:
                cs_precedes = conv.get('p_cs_precedes', 1)
                sep_by_space = conv.get('p_sep_by_space', 1)
            else:
                cs_precedes = conv.get('n_cs_precedes', 1)
                sep_by_space = conv.get('n_sep_by_space', 1)

            if sep_by_space:
                space = ' '
            else:
                space = ''
            if cs_precedes:
                currency = currency_symbol + space + currency
            else:
                currency = currency + space + currency_symbol

        return currency

    def __repr__(self):
        return '<currency %s>' % self.format()

_DecimalConverter = type(converter.get_converter(Decimal))

class _CurrencyConverter(_DecimalConverter):
    type = currency
    name = _('Currency')
    align = Alignment.RIGHT

    def __init__(self):
        self.symbol = True
        self.precision = 2

    def as_string(self, value, format=None, symbol=None, precision=None):
        if value == ValueUnset:
            return ''

        if not isinstance(value, currency):
            try:
                value = currency(value)
            except ValueError:
                raise ValidationError(
                    _("%s can not be converted to a currency") % value)

        if symbol is None:
            symbol = self.symbol

        if precision is None:
            precision = self.precision

        return value.format(symbol, precision)

    def from_string(self, value):
        if value == '':
            return ValueUnset
        try:
            return currency(value)
        except (ValueError, InvalidOperation):
            raise ValidationError(
                _("%s can not be converted to a currency") % value)

converter.add(_CurrencyConverter)


def format_price(value, symbol=True, precision=None):
    """
    Formats a price according to the current locales monetary
    settings

    @param value: number
    @param symbol: whether to include the currency symbol
    """

    return currency(value).format(symbol, precision)