Python decimal.Context() Examples
The following are 30
code examples of decimal.Context().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
decimal
, or try the search function
.
Example #1
Source File: tools.py From aioquant with MIT License | 6 votes |
def float_to_str(f, p=20): """Convert the given float to a string, without resorting to scientific notation. Args: f: Float params. p: Precision length. Returns: s: String format data. """ if type(f) == str: f = float(f) ctx = decimal.Context(p) d1 = ctx.create_decimal(repr(f)) s = format(d1, 'f') return s
Example #2
Source File: test_decimal.py From recruit with Apache License 2.0 | 6 votes |
def test_astype_dispatches(frame): # This is a dtype-specific test that ensures Series[decimal].astype # gets all the way through to ExtensionArray.astype # Designing a reliable smoke test that works for arbitrary data types # is difficult. data = pd.Series(DecimalArray([decimal.Decimal(2)]), name='a') ctx = decimal.Context() ctx.prec = 5 if frame: data = data.to_frame() result = data.astype(DecimalDtype(ctx)) if frame: result = result['a'] assert result.dtype.context.prec == ctx.prec
Example #3
Source File: test_decimal.py From coffeegrindsize with MIT License | 6 votes |
def test_astype_dispatches(frame): # This is a dtype-specific test that ensures Series[decimal].astype # gets all the way through to ExtensionArray.astype # Designing a reliable smoke test that works for arbitrary data types # is difficult. data = pd.Series(DecimalArray([decimal.Decimal(2)]), name='a') ctx = decimal.Context() ctx.prec = 5 if frame: data = data.to_frame() result = data.astype(DecimalDtype(ctx)) if frame: result = result['a'] assert result.dtype.context.prec == ctx.prec
Example #4
Source File: test_cast.py From ibis with Apache License 2.0 | 6 votes |
def test_cast_to_decimal(t, df, type): expr = t.float64_as_strings.cast(type) result = expr.execute() context = decimal.Context(prec=type.precision) expected = df.float64_as_strings.apply( lambda x: context.create_decimal(x).quantize( decimal.Decimal( '{}.{}'.format( '0' * (type.precision - type.scale), '0' * type.scale ) ) ) ) tm.assert_series_equal(result, expected) assert all( abs(element.as_tuple().exponent) == type.scale for element in result.values ) assert all( 1 <= len(element.as_tuple().digits) <= type.precision for element in result.values )
Example #5
Source File: test_functions.py From ibis with Apache License 2.0 | 6 votes |
def test_math_functions_decimal(t, df, ibis_func, pandas_func): dtype = dt.Decimal(12, 3) result = ibis_func(t.float64_as_strings.cast(dtype)).execute() context = decimal.Context(prec=dtype.precision) expected = df.float64_as_strings.apply( lambda x: context.create_decimal(x).quantize( decimal.Decimal( '{}.{}'.format( '0' * (dtype.precision - dtype.scale), '0' * dtype.scale ) ) ) ).apply(pandas_func) result[result.apply(math.isnan)] = -99999 expected[expected.apply(math.isnan)] = -99999 tm.assert_series_equal(result, expected)
Example #6
Source File: test_decimal.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 6 votes |
def test_astype_dispatches(frame): # This is a dtype-specific test that ensures Series[decimal].astype # gets all the way through to ExtensionArray.astype # Designing a reliable smoke test that works for arbitrary data types # is difficult. data = pd.Series(DecimalArray([decimal.Decimal(2)]), name='a') ctx = decimal.Context() ctx.prec = 5 if frame: data = data.to_frame() result = data.astype(DecimalDtype(ctx)) if frame: result = result['a'] assert result.dtype.context.prec == ctx.prec
Example #7
Source File: _compat.py From bazarr with GNU General Public License v3.0 | 5 votes |
def round_py2_compat(what): """ Python 2 and Python 3 use different rounding strategies in round(). This function ensures that results are python2/3 compatible and backward compatible with previous py2 releases :param what: float :return: rounded long """ d = Context( prec=len(str(long(what))), # round to integer with max precision rounding=decimal.ROUND_HALF_UP ).create_decimal(str(what)) # str(): python 2.6 compat return long(d)
Example #8
Source File: base.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def _get_decimal_converter(precision, scale): if scale == 0: return int context = decimal.Context(prec=precision) quantize_value = decimal.Decimal(1).scaleb(-scale) return lambda v: decimal.Decimal(v).quantize(quantize_value, context=context)
Example #9
Source File: __init__.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def context(self): return decimal.Context(prec=self.max_digits)
Example #10
Source File: decimal128.py From opsbro with MIT License | 5 votes |
def create_decimal128_context(): """Returns an instance of :class:`decimal.Context` appropriate for working with IEEE-754 128-bit decimal floating point values. """ opts = _CTX_OPTIONS.copy() opts['traps'] = [] return decimal.Context(**opts)
Example #11
Source File: write.py From ditto with BSD 3-Clause "New" or "Revised" License | 5 votes |
def float_to_str(self, f): """ Used to create floats without being in scientific notation""" ctx = decimal.Context() d1 = ctx.create_decimal(repr(f)) return format(d1, "f")
Example #12
Source File: notation.py From python-ballpark with ISC License | 5 votes |
def engineering(value, precision=3, prefix=False, prefixes=SI): """ Convert a number to engineering notation. """ display = decimal.Context(prec=precision) value = decimal.Decimal(value).normalize(context=display) string = value.to_eng_string() if prefix: prefixes = {e(exponent): prefix for exponent, prefix in prefixes.items()} return replace(string, prefixes) else: return string
Example #13
Source File: _compat.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def round_py2_compat(what): """ Python 2 and Python 3 use different rounding strategies in round(). This function ensures that results are python2/3 compatible and backward compatible with previous py2 releases :param what: float :return: rounded long """ d = Context( prec=len(str(long(what))), # round to integer with max precision rounding=decimal.ROUND_HALF_UP ).create_decimal(str(what)) # str(): python 2.6 compat return long(d)
Example #14
Source File: _compat.py From script.elementum.burst with Do What The F*ck You Want To Public License | 5 votes |
def round_py2_compat(what): """ Python 2 and Python 3 use different rounding strategies in round(). This function ensures that results are python2/3 compatible and backward compatible with previous py2 releases :param what: float :return: rounded long """ d = Context( prec=len(str(long(what))), # round to integer with max precision rounding=decimal.ROUND_HALF_UP ).create_decimal(str(what)) # str(): python 2.6 compat return long(d)
Example #15
Source File: read.py From stempeg with MIT License | 5 votes |
def float_to_str(f, precision=5): """ Convert the given float to a string, without resorting to scientific notation """ # create a new context for this task ctx = decimal.Context(rounding=decimal.ROUND_DOWN) # 12 digits should be enough to represent a single sample of # 192khz in float ctx.prec = precision d1 = ctx.create_decimal(repr(round(f, 5))) return format(d1, 'f')
Example #16
Source File: utils.py From business-rules with MIT License | 5 votes |
def float_to_decimal(f): """ Convert a floating point number to a Decimal with no loss of information. Intended for Python 2.6 where casting float to Decimal does not work. """ n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) ctx = Context(prec=60) result = ctx.divide(numerator, denominator) while ctx.flags[Inexact]: ctx.flags[Inexact] = False ctx.prec *= 2 result = ctx.divide(numerator, denominator) return result
Example #17
Source File: decimal128.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def create_decimal128_context(): """Returns an instance of :class:`decimal.Context` appropriate for working with IEEE-754 128-bit decimal floating point values. """ opts = _CTX_OPTIONS.copy() opts['traps'] = [] return decimal.Context(**opts)
Example #18
Source File: operations.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def get_decimalfield_converter(self, expression): # SQLite stores only 15 significant digits. Digits coming from # float inaccuracy must be removed. create_decimal = decimal.Context(prec=15).create_decimal_from_float if isinstance(expression, Col): quantize_value = decimal.Decimal(1).scaleb(-expression.output_field.decimal_places) def converter(value, expression, connection): if value is not None: return create_decimal(value).quantize(quantize_value, context=expression.output_field.context) else: def converter(value, expression, connection): if value is not None: return create_decimal(value) return converter
Example #19
Source File: decimal128.py From learn_python3_spider with MIT License | 5 votes |
def create_decimal128_context(): """Returns an instance of :class:`decimal.Context` appropriate for working with IEEE-754 128-bit decimal floating point values. """ opts = _CTX_OPTIONS.copy() opts['traps'] = [] return decimal.Context(**opts)
Example #20
Source File: value_cache.py From RAFCON with Eclipse Public License 1.0 | 5 votes |
def __init__(self, precision=2): self.empty() self._context = Context(prec=precision)
Example #21
Source File: tools.py From thenextquant with MIT License | 5 votes |
def float_to_str(f, p=20): """ Convert the given float to a string, without resorting to scientific notation. @param f 浮点数参数 @param p 精读 """ if type(f) == str: f = float(f) ctx = decimal.Context(p) d1 = ctx.create_decimal(repr(f)) return format(d1, 'f')
Example #22
Source File: __init__.py From minter-sdk with MIT License | 5 votes |
def to_bip(value): """ Convert PIPs to BIPs. Use dynamic Decimal precision, depending on value length. Args: value (int|str|Decimal): value in PIP Returns: Decimal """ # Check if value is correct PIP value value = str(value) if not value.isdigit(): raise ValueError(f'{value} is not correct PIP value') # Get default decimal context context = decimal.getcontext() # Set temporary decimal context for calculation decimal.setcontext( decimal.Context(prec=len(value), rounding=decimal.ROUND_DOWN) ) # Convert value value = decimal.Decimal(value) / decimal.Decimal(PIP) # Reset decimal context to default decimal.setcontext(context) return value
Example #23
Source File: __init__.py From minter-sdk with MIT License | 5 votes |
def convert_value(cls, value, to, prec=33): """ Convert values from/to pip/bip. Args: value (string|int|Decimal|float): value to convert to (string): coin to convert value to prec (int): decimal context precision (decimal number length) Returns: int|Decimal """ # Get default decimal context context = decimal.getcontext() # Set temporary decimal context for calculation decimal.setcontext( decimal.Context(prec=prec, rounding=decimal.ROUND_DOWN) ) # PIP in BIP in Decimal default = decimal.Decimal(str(cls.DEFAULT)) # Value in Decimal value = decimal.Decimal(str(value)) # Make conversion if to == 'pip': value = int(value * default) elif to == 'bip': value /= default # Reset decimal context to default decimal.setcontext(context) return value
Example #24
Source File: time_estimates.py From zxcvbn-python with MIT License | 5 votes |
def float_to_decimal(f): "Convert a floating point number to a Decimal with no loss of information" n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) ctx = Context(prec=60) result = ctx.divide(numerator, denominator) while ctx.flags[Inexact]: ctx.flags[Inexact] = False ctx.prec *= 2 result = ctx.divide(numerator, denominator) return result
Example #25
Source File: decimal.py From ibis with Apache License 2.0 | 5 votes |
def execute_cast_series_to_decimal(op, data, type, **kwargs): precision = type.precision scale = type.scale context = decimal.Context(prec=precision) places = context.create_decimal( '{}.{}'.format('0' * (precision - scale), '0' * scale) ) return data.apply( lambda x, context=context, places=places: ( # noqa: E501 context.create_decimal(x).quantize(places) ) )
Example #26
Source File: __init__.py From bioforum with MIT License | 5 votes |
def context(self): return decimal.Context(prec=self.max_digits)
Example #27
Source File: decimal128.py From vnpy_crypto with MIT License | 5 votes |
def create_decimal128_context(): """Returns an instance of :class:`decimal.Context` appropriate for working with IEEE-754 128-bit decimal floating point values. """ opts = _CTX_OPTIONS.copy() opts['traps'] = [] return decimal.Context(**opts)
Example #28
Source File: tools.py From thenextquant with MIT License | 5 votes |
def float_to_str(f, p=20): """ Convert the given float to a string, without resorting to scientific notation. @param f 浮点数参数 @param p 精读 """ if type(f) == str: f = float(f) ctx = decimal.Context(p) d1 = ctx.create_decimal(repr(f)) return format(d1, 'f')
Example #29
Source File: operation.py From py-stellar-base with Apache License 2.0 | 4 votes |
def to_xdr_amount(value: Union[str, Decimal]) -> int: """Converts an amount to the appropriate value to send over the network as a part of an XDR object. Each asset amount is encoded as a signed 64-bit integer in the XDR structures. An asset amount unit (that which is seen by end users) is scaled down by a factor of ten million (10,000,000) to arrive at the native 64-bit integer representation. For example, the integer amount value 25,123,456 equals 2.5123456 units of the asset. This scaling allows for seven decimal places of precision in human-friendly amount units. This static method correctly multiplies the value by the scaling factor in order to come to the integer value used in XDR structures. See `Stellar's documentation on Asset Precision <https://www.stellar.org/developers/guides/concepts/assets.html#amount-precision-and-representation>`_ for more information. :param value: The amount to convert to an integer for XDR serialization. """ if not (isinstance(value, str) or isinstance(value, Decimal)): raise TypeError( "Value of type '{}' must be of type {} or {}, but got {}.".format( value, str, Decimal, type(value) ) ) # throw exception if value * ONE has decimal places (it can't be represented as int64) try: amount = int( (Decimal(value) * Operation._ONE).to_integral_exact( context=Context(traps=[Inexact]) ) ) except decimal.Inexact: raise ValueError( "Value of '{}' must have at most 7 digits after the decimal.".format( value ) ) if amount < 0 or amount > 9223372036854775807: raise ValueError( "Value of '{}' must represent a positive number " "and the max valid value is 922337203685.4775807.".format(value) ) return amount
Example #30
Source File: notation.py From python-ballpark with ISC License | 4 votes |
def scientific(value, precision=3): display = decimal.Context(prec=precision) value = decimal.Decimal(value).normalize(context=display) return display.to_sci_string(value)