## 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

### Problem

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

### Solution

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

````>>> ``round``(``1.23``,` `1``)`
`1.2`
`>>> ``round``(``1.27``,` `1``)`
`1.3`
`>>> ``round``(``-``1.27``,` `1``)`
`-1.3`
`>>> ``round``(``1.25361``,``3``)`
`1.254`
`>>>````

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``)`
`1627730`
`>>> ``round``(``a``,` `-``2``)`
`1627700`
`>>> ``round``(``a``,` `-``3``)`
`1628000`
`>>>````

### Discussion

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'``)`
`'1.23'`
`>>> ``format``(``x``,` `'0.3f'``)`
`'1.235'`
`>>> ``'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 the O’Reilly learning platform.

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