def prettify_float(real: float, precision: int = 2) -> str:
'''
Prettify the passed floating-point number into a human-readable string,
rounded and truncated to the passed number of decimal places.
This converter prettifies floating-point numbers for human consumption,
producing more readable results than the default :meth:`float.__str__`
dunder method. Notably, this converter:
* Strips all ignorable trailing zeroes and decimal points from this number
(e.g., ``3`` rather than either ``3.`` or ``3.0``).
* Rounds to the passed precision for perceptual uniformity.
Parameters
----------
real : float
Arbitrary floating-point number to be prettified.
precision : int, optional
**Precision** (i.e., number of decimal places to round to). Defaults to
a precision of 2 decimal places.
Returns
----------
str
Human-readable string prettified from this floating-point number.
Raises
----------
ValueError
If this precision is negative.
'''
# If this precision is negative, raise an exception.
if precision < 0:
raise ValueError(f'Negative precision {precision} unsupported.')
# Else, this precision is non-negative.
# String prettified from this floating-point number. In order:
# * Coerce this number into a string rounded to this precision.
# * Truncate all trailing zeroes from this string.
# * Truncate any trailing decimal place if any from this string.
result = f'{real:.{precision}f}'.rstrip('0').rstrip('.')
# If rounding this string from a small negative number (e.g., "-0.001")
# yielded the anomalous result of "-0", return "0" instead; else, return
# this result as is.
return '0' if result == '-0' else result
不要相信我的谎言
__abc0风格的单元测试或它没有发生。
def test_prettify_float() -> None:
'''
Test usage of the :func:`prettify_float` prettifier.
'''
# Defer test-specific imports.
from pytest import raises
# Assert this function prettifies zero as expected.
assert prettify_float(0.0) == '0'
# Assert this function prettifies a negative integer as expected.
assert prettify_float(-2.0) == '-2'
# Assert this prettifier prettifies a small negative float as expected.
assert prettify_float(-0.001) == '0'
# Assert this prettifier prettifies a larger negative float as expected.
assert prettify_float(-2.718281828) == '-2.72'
assert prettify_float(-2.718281828, precision=4) == '-2.7183'
# Assert this function prettifies a positive integer as expected.
assert prettify_float(3.0) == '3'
# Assert this function prettifies a positive float as expected.
assert prettify_float(3.14159265359) == '3.14'
assert prettify_float(3.14159265359, precision=4) == '3.1416'
# Assert this prettifier raises the expected exception when passed a
# negative precision.
with raises(ValueError):
prettify_float(2.718281828, precision=-2)