Home > Backend Development > Python Tutorial > Summary of several methods of rounding in Python

Summary of several methods of rounding in Python

高洛峰
Release: 2017-01-09 11:53:33
Original
3265 people have browsed it

Preface

For every programmer, data processing is inevitable during the programming process. In many cases, the obtained data needs to be processed according to requirements. Rounding is the most basic. data processing. Rounding methods include rounding down, rounding up, rounding up, etc. Let’s take a look at several methods of rounding in Python.

1. Round down

To round down, just use the built-in int() function:

>>> a = 3.75
>>> int(a)
3
Copy after login

2. Rounding

Use the round() function to round numbers:

>>> round(3.25); round(4.85)
3.0
5.0
Copy after login

3. Up Rounding

To round up, you need to use the ceil() method in the math module:

>>> import math
>>> math.ceil(3.25)
4.0
>>> math.ceil(3.75)
4.0
>>> math.ceil(4.85)
5.0
Copy after login

4. Round the integers separately Part and decimal part

Sometimes we may need to obtain the integer part and the decimal part separately. In this case, we can use the modf() method in the math module. This method returns a decimal part and an integer part. Tuple:

>>> import math
>>> math.modf(3.25)
(0.25, 3.0)
>>> math.modf(3.75)
(0.75, 3.0)
>>> math.modf(4.2)
(0.20000000000000018, 4.0)
Copy after login

Some people may be surprised by the last output result. Logically speaking, it should return (0.2, 4.0). This involves another problem, that is, the representation of floating point numbers in computers cannot accurately represent decimals in computers, at least current computers cannot do this. The final output result in the above example is just an approximate representation of 0.2 in the calculation. Python, like C, uses the IEEE 754 specification to store floating point numbers.

Summary

The above is all about several rounding methods in Python. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can Leave messages to communicate.

For more summary of several methods of rounding in Python and related articles, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template