Round a Number

rounded_value(number, precision=4)

Rounds a number to a certain decimal place, but returns a non-zero result if the number being rounded is non-zero even if it would round to zero at that level of decimal precision; allows None as a possible input

Parameters
  • number (int or float) – Number to round

  • precision (int, default=4) – Maximum number of digits that can appear after the decimal place of the result

Raises
  • TypeError – First argument must be an integer, a float, or None

  • ValueError – Last argument must be a positive integer

Returns

number – Original number rounded to the number of decimal places indicated by the precision input

Return type

float

Notes

  • Number to round: \(n\)

  • Absolute value of number: \(a = |n|\)

  • Maximum number of digits after decimal place of result: \(d\)

  • Check size of number: \(c(a,d) = \lfloor a\cdot{10^d} \rfloor\)

  • Significant digit: \(s(a,d) = \lfloor ( a\cdot{10^d} - \lfloor a\cdot{10^d} \rfloor )\cdot{10} \rfloor\)

  • If \(c(a,d) = 0\):

    • Rounding formula (if \(n = 0\)): \(r = 0\)

    • If \(n \neq 0\):

      • Rounding formula (if \(a = n\)): \(r(d) = 10^{-d}\)

      • Rounding formula (if \(a \neq n\)): \(r(d) = -10^{-d}\)

  • If \(c(a,d) \neq 0\):

    • If \(a = n\):

      • Rounding formula (if \(s(a,d) \geq 5\)): \(r(a,d) = \frac{\lceil a\cdot{10^d} \rceil}{10^d}\)

      • Rounding formula (if \(s(a,d) < 5\)): \(r(a,d) = \frac{\lfloor a\cdot{10^d} \rfloor}{10^d}\)

    • If \(a \neq n\):

      • Rounding formula (if \(s(a,d) \geq 5\)): \(r(a,d) = -\frac{\lceil a\cdot{10^d} \rceil}{10^d}\)

      • Rounding formula (if \(s(a,d) < 5\)): \(r(a,d) = -\frac{\lfloor a\cdot{10^d} \rfloor}{10^d}\)

  • Rounding

Examples

Import rounded_value function from regressions library
>>> from regressions.statistics.rounding import rounded_value
Round the number 9.2157823956916472 to six decimal places
>>> number_normal = rounded_value(9.2157825956916472, 6)
>>> print(number_normal)
9.215783
Round the number -0.00000003 to six decimal places
>>> number_abnormal = rounded_value(-0.00000003, 6)
>>> print(number_abnormal)
-1e-6
Round the number 11.725371548561 to four decimal places (without providing a value for the precision argument)
>>> round_skip = rounded_value(11.725371548561)
>>> print(round_skip)
11.7254