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

Function _round_to_exponent

Lib/fractions.py:73–99  ·  view source on GitHub ↗

Round a rational number to the nearest multiple of a given power of 10. Rounds the rational number n/d to the nearest integer multiple of 10**exponent, rounding to the nearest even integer multiple in the case of a tie. Returns a pair (sign: bool, significand: int) representing the

(n, d, exponent, no_neg_zero=False)

Source from the content-addressed store, hash-verified

71# Helpers for formatting
72
73def _round_to_exponent(n, d, exponent, no_neg_zero=False):
74 """Round a rational number to the nearest multiple of a given power of 10.
75
76 Rounds the rational number n/d to the nearest integer multiple of
77 10**exponent, rounding to the nearest even integer multiple in the case of
78 a tie. Returns a pair (sign: bool, significand: int) representing the
79 rounded value (-1)**sign * significand * 10**exponent.
80
81 If no_neg_zero is true, then the returned sign will always be False when
82 the significand is zero. Otherwise, the sign reflects the sign of the
83 input.
84
85 d must be positive, but n and d need not be relatively prime.
86 """
87 if exponent >= 0:
88 d *= 10**exponent
89 else:
90 n *= 10**-exponent
91
92 # The divmod quotient is correct for round-ties-towards-positive-infinity;
93 # In the case of a tie, we zero out the least significant bit of q.
94 q, r = divmod(n + (d >> 1), d)
95 if r == 0 and d & 1 == 0:
96 q &= -2
97
98 sign = q < 0 if no_neg_zero else n < 0
99 return sign, abs(q)
100
101
102def _round_to_figures(n, d, figures):

Callers 2

_round_to_figuresFunction · 0.85
_format_float_styleMethod · 0.85

Calls 1

absFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…