liveBook · Manning

Number rounding

As explained in Get Programming: Learn to code with Python

A Python built-in function that returns a number rounded to a specified precision or to the nearest whole-number value by default.

Python’s built-in round() turns a calculated number into a rounded value. With no additional precision, it is used to obtain a whole-number result. section 6.4

Rounding is especially useful after calculations with decimal values. Floating-point numbers can be stored as close approximations, so a result expected to be 3 might appear as 2.9999999999999893. Applying round() removes this distracting precision error for the final integer result. section 6.4

Converting decimal hours into minutes

minutes_decimal = hours_decimal - hours_part minutes_part = round(minutes_decimal * 60) If hours_decimal is 2.05 and hours_part is 2, minutes_decimal is 0.05. Multiplying by 60 produces approximately 3, and round() stores the useful whole-minute result as 3. section 6.4

Do not confuse rounding with int(). Converting 3.94 with int() truncates the decimal part and produces 3; round() is chosen when the nearest whole-number result is wanted. section 5.3 section 6.4

minutes_part = round(minutes_decimal * 60)

See the compact calculation that multiplies the decimal part by 60 and rounds the result. section 6.4

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains the call through a worked conversion and floating-point rationale, but does not develop broader rounding rules.
Examples
Demonstrates round() while converting 123 minutes into 2 hours and 3 minutes.
What it assumes
Assumes basic arithmetic, variables, decimal values, and int(); distinguishes rounding from truncating a float.
What you can do after
Apply round() to correct small floating-point discrepancies when a calculation should produce a whole-number result.
How it connects
Connects rounding with floating-point numbers, arithmetic expressions, type conversion, and integer truncation.

Also explained in

Compare how 4 books explain number rounding →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.