Chapter 3. Numbers, Dates, and Times

Performing mathematical calculations with integers and floating-point numbers is easy in Python. However, if you need to perform calculations with fractions, arrays, or dates and times, a bit more work is required. The focus of this chapter is on such topics.

3.1. Rounding Numerical Values


You want to round a floating-point number to a fixed number of decimal places.


For simple rounding, use the built-in round(value, ndigits) function. For example:

>>> round(1.23, 1)
>>> round(1.27, 1)
>>> round(-1.27, 1)
>>> round(1.25361,3)

When a value is exactly halfway between two choices, the behavior of round is to round to the nearest even digit. That is, values such as 1.5 or 2.5 both get rounded to 2.

The number of digits given to round() can be negative, in which case rounding takes place for tens, hundreds, thousands, and so on. For example:

>>> a = 1627731
>>> round(a, -1)
>>> round(a, -2)
>>> round(a, -3)


Don’t confuse rounding with formatting a value for output. If your goal is simply to output a numerical value with a certain number of decimal places, you don’t typically need to use round(). Instead, just specify the desired precision when formatting. For example:

>>> x = 1.23456
>>> format(x, '0.2f')
>>> format(x, '0.3f')
>>> 'value is {:0.3f}'.format(x)
'value is 1.235'

Also, resist the urge to round floating-point numbers to “fix” perceived accuracy problems. ...

Get Python Cookbook, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.