autograder.util.math
1import math 2import typing 3 4DEFAULT_FORMAT_PRECISION: int = 2 5 6def number_to_str( 7 number: typing.Union[int, float], 8 precision: int = DEFAULT_FORMAT_PRECISION, 9 exact_precision: bool = False, 10 ) -> str: 11 """ 12 Convert a number to a string. 13 If the number is a float, use the given precision to round the number. 14 15 When `exact_precision` is set, the input will be turned into an int and formatted with that exact precision. 16 Otherwise, smallest precision possible will be used (while still keeping the value of the input). 17 """ 18 19 precision = max(0, precision) 20 21 if (not exact_precision): 22 for effective_precision in range(precision): 23 rounded_number: typing.Union[float, int] = round(number, effective_precision) 24 if (math.isclose(number, rounded_number)): 25 if (effective_precision == 0): 26 rounded_number = int(rounded_number) 27 28 return str(rounded_number) 29 30 return "{number:0.{precision}f}".format(number = round(float(number), precision), precision = precision) # pylint: disable=consider-using-f-string
DEFAULT_FORMAT_PRECISION: int =
2
def
number_to_str( number: Union[int, float], precision: int = 2, exact_precision: bool = False) -> str:
7def number_to_str( 8 number: typing.Union[int, float], 9 precision: int = DEFAULT_FORMAT_PRECISION, 10 exact_precision: bool = False, 11 ) -> str: 12 """ 13 Convert a number to a string. 14 If the number is a float, use the given precision to round the number. 15 16 When `exact_precision` is set, the input will be turned into an int and formatted with that exact precision. 17 Otherwise, smallest precision possible will be used (while still keeping the value of the input). 18 """ 19 20 precision = max(0, precision) 21 22 if (not exact_precision): 23 for effective_precision in range(precision): 24 rounded_number: typing.Union[float, int] = round(number, effective_precision) 25 if (math.isclose(number, rounded_number)): 26 if (effective_precision == 0): 27 rounded_number = int(rounded_number) 28 29 return str(rounded_number) 30 31 return "{number:0.{precision}f}".format(number = round(float(number), precision), precision = precision) # pylint: disable=consider-using-f-string
Convert a number to a string. If the number is a float, use the given precision to round the number.
When exact_precision is set, the input will be turned into an int and formatted with that exact precision.
Otherwise, smallest precision possible will be used (while still keeping the value of the input).