"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Round Numbers to a Specific Base in Python (Not Just 5)?

How to Round Numbers to a Specific Base in Python (Not Just 5)?

Published on 2024-11-02
Browse:845

How to Round Numbers to a Specific Base in Python (Not Just 5)?

Round to 5 (or other number) in Python

In Python, the built-in round function rounds to the nearest integer. However, it is possible to create a custom function that rounds to a specific number (such as 5) using the following approach:

Python 3

def myround(x, base=5):
    return base * round(x/base)

This function works by first dividing the input number x by the base number (5 by default). This ensures that the resulting number is an integer, correctly rounded. The function then multiplies the rounded number by the base number to obtain the rounded result.

Python 2

In Python 2, the float() function must be used to ensure that the division operation (/) performs floating-point division. Additionally, a final conversion to int is necessary because round() returns a floating-point value in Python 2.

def myround(x, base=5):
    return int(base * round(float(x)/base))

By providing a base parameter with a default value of 5, the function becomes more generic, allowing it to round to any desired number.

This custom function can be used to round numbers to any specified number, not just 5. For example, the following code rounds numbers to the nearest 10:

myround(23, 10)  # Output: 20
myround(47, 10)  # Output: 50
Release Statement This article is reprinted at: 1729212915 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3