How to Solve Python Integer Rounding Problems with Simple Functions
This article walks through a common Python integer‑rounding challenge, explains why a naïve implementation fails for certain inputs, and presents three concise solutions—including a math.ceil approach and a ternary expression—complete with runnable code snippets and visual examples.
1. Introduction
Hello, I am a Python enthusiast. Recently a follower asked a basic Python rounding question in a chat group, which is illustrated in the screenshots below.
2. Implementation Process
The initial solution attempted to use a series of conditional returns:
def brf_cnt(consume_number):
if abs(consume_number) < 13:
return 1
elif 13 <= abs(consume_number) < 21:
return 2
else:
return consume_number // 10 + 1
if __name__ == '__main__':
consume_number = 33
print(brf_cnt(consume_number))This works for many cases but fails when the input is 30 (expected 3, got 4). A corrected approach uses math.ceil to round up:
import math
cl = math.ceil
nums = [10, 13, 20, 21, 30, 31, 33]
for i in nums:
if i < 13:
print(1)
else:
print(cl(i/10))Another contributor offered a similar solution, and a third version simplifies the logic with a ternary expression:
def money_people(x):
return 1 if x < 13 else (x - 1) // 10 + 1
print(money_people(20))All three implementations satisfy the problem requirements, as shown in the following screenshots:
3. Summary
This article presented a basic Python rounding problem, analyzed why the first attempt produced incorrect results, and provided three clean solutions—including a math.ceil method and a ternary operator version—helping readers quickly resolve similar issues.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
