libb.round_digit_string

round_digit_string(s, places=None)[source]

Round a numeric string to a number of decimal places, digit exact.

A whole value comes back as a plain integer, with leading zeros and a trailing .0 dropped. Any other value comes back in plain notation, with trailing zeros dropped. s comes back unchanged when it is not a finite number, or when the result written out needs more than ROUND_CONTEXT.prec (28) digits. A dropped trailing zero never counts, except while rounding: places that pad the value past 28 digits also return s. The caller’s decimal context has no effect.

Parameters:
  • s (str) – A number as text, plain or exponent form. Never an identifier, since leading zeros are dropped.

  • places (int) – Decimal places to round to, half to even. A negative value rounds left of the point. None or 0 keeps every digit, and a whole value ignores it.

Returns:

Rounded numeric string, or s stripped.

Return type:

str

Example:

>>> round_digit_string('7283.1234', 3)
'7283.123'
>>> round_digit_string('7283.1234', None)
'7283.1234'
>>> round_digit_string('7283', 3)
'7283'
>>> round_digit_string('9007199254740993')
'9007199254740993'
>>> round_digit_string('inf')
'inf'
>>> round_digit_string('1e400')
'1e400'