Python Round Function With Examples

Posted in

Python Round Function With Examples
vinaykhatri

Vinay Khatri
Last updated on December 22, 2024

    In Python, we have many we have various data types such as int, float, str, etc. And for every data type, we have multiple in-built functions. One of those functions is round(), which return a rounded value for a floating-point number.

    Python Round Function

    Syntax

    round(number, digits)

    round() Parameters

    The round() function can accepts two parameters.

    • The number which round value supposed to evaluate.
    • The digit parameter specifies the value up to which the number is supposed to round. By default, the digit value is 0.

    Return value of round() function

    • For round(number) it would return the nearest rounded integer value.
    • For round ( number, digit ) it would return a floating-point rounded version of the number . The digit represents the number of decimals should be present in the returned number. By default, the digit value is zero which lead to 0 decimal number or integer.

    Example

    # if number is a float.
    >>> round(20.1)
    20
    
    >>> round(20.4)
    20
    
    >>> round(20.5)
    20
    
    >>> round(20.6)
    21
    
    >>> round(20.9)
    21 
    #if number is an integer
    >>> round(20)
    20
    
    >>> round(21)
    21
    #if number is a string data type
    >>> round("21.1")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: type str doesn't define __round__ method

    < Note >: The round function only accepts int and float data type.

    round(number, digit) Example

    The digit parameter signifies the number of decimal digits up to which the specified number ti be round of.

    Example:

    >>> round(1.3333333, 1)
    1.3
    
    >>> round(1.33333, 2)
    1.33
    
    >>> round(1.3333333, 3)
    1.333

    Summary

    • round() function return the nearest rounded value for the specified number.
    • It accepts two parameters, the specified number and number of decimal digits .
    • the round() function accepts only integer and floating-point numbers.

    People are also reading:

    Leave a Comment on this Post

    0 Comments