## Python cookbook 3rd note (3.1): rounding numbers

Giant ship 2020-11-16 01:07:12
python cookbook 3rd rd note

# Rounding of numbers

## problem

You want to round floating-point numbers to the specified precision .

## solution

For simple rounding operations , Use the built-in round(value, ndigits) Function . such as ：

``````>>> 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 just in the middle of two boundaries , round Function returns the nearest even number . in other words , Yes 1.5 perhaps 2.5 All the rounding operations of will get 2.

Pass to round() Functional ndigits The parameter can be negative , In this case , Rounding works on the tens 、 Hundred bit 、 Thousands, etc . such as ：

``````>>> a = 1627731
>>> round(a, -1)
1627730
>>> round(a, -2)
1627700
>>> round(a, -3)
1628000
>>>
``````

## Discuss

Don't confuse rounding with formatting output . If your goal is simply to output a certain width of number , You don't need to use round() function . Just specify the precision when formatting . such as ：

``````>>> 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'
>>>
``````

Again , Don't try to round floating-point values ” correct ” The seemingly right question . such as , You may be inclined to do this ：

``````>>> a = 2.1
>>> b = 4.2
>>> c = a + b
>>> c
6.300000000000001
>>> c = round(c, 2) # "Fix" result (???)
>>> c
6.3
>>>
``````

For most programs that use floating points , It's not necessary and not recommended . Although there will be a little bit of error in the calculation , But these small errors can be understood and tolerated . If such small errors cannot be allowed ( For example, when it comes to finance ), Then consider using it decimal Module .