MCPcopy Index your code
hub / github.com/python/cpython / currency

Function currency

Lib/locale.py:255–300  ·  view source on GitHub ↗

Formats val according to the currency settings in the current locale.

(val, symbol=True, grouping=False, international=False)

Source from the content-addressed store, hash-verified

253 return new_f % val
254
255def currency(val, symbol=True, grouping=False, international=False):
256 """Formats val according to the currency settings
257 in the current locale."""
258 conv = localeconv()
259
260 # check for illegal values
261 digits = conv[international and 'int_frac_digits' or 'frac_digits']
262 if digits == 127:
263 raise ValueError("Currency formatting is not possible using "
264 "the 'C' locale.")
265
266 s = _localize(f'{abs(val):.{digits}f}', grouping, monetary=True)
267 # '<' and '>' are markers if the sign must be inserted between symbol and value
268 s = '<' + s + '>'
269
270 if symbol:
271 smb = conv[international and 'int_curr_symbol' or 'currency_symbol']
272 precedes = conv[val<0 and 'n_cs_precedes' or 'p_cs_precedes']
273 separated = conv[val<0 and 'n_sep_by_space' or 'p_sep_by_space']
274
275 if precedes:
276 s = smb + (separated and ' ' or '') + s
277 else:
278 if international and smb[-1] == ' ':
279 smb = smb[:-1]
280 s = s + (separated and ' ' or '') + smb
281
282 sign_pos = conv[val<0 and 'n_sign_posn' or 'p_sign_posn']
283 sign = conv[val<0 and 'negative_sign' or 'positive_sign']
284
285 if sign_pos == 0:
286 s = '(' + s + ')'
287 elif sign_pos == 1:
288 s = sign + s
289 elif sign_pos == 2:
290 s = s + sign
291 elif sign_pos == 3:
292 s = s.replace('<', sign)
293 elif sign_pos == 4:
294 s = s.replace('>', sign)
295 else:
296 # the default if nothing specified;
297 # this should be the most fitting sign position
298 s = sign + s
299
300 return s.replace('<', '').replace('>', '')
301
302def str(val):
303 """Convert float to string, taking the locale into account."""

Callers

nothing calls this directly

Calls 4

localeconvFunction · 0.85
_localizeFunction · 0.85
absFunction · 0.85
replaceMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…