Home  >  Article  >  Backend Development  >  How to retain integers in python

How to retain integers in python

(*-*)浩
(*-*)浩Original
2019-07-03 11:22:3519496browse

Python Several Rounding Methods

Data processing is inevitable in programming. In many cases, it is necessary to process the obtained data according to requirements. Rounding is the most effective method. Basic data processing. Rounding methods include rounding down, rounding up, rounding up, etc.

How to retain integers in python

1. Round down (recommended learning: Python video tutorial)

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

>>> a = 3.75
>>> int(a)

2. Rounding

To round numbers, use the round() function:

>>> round(3.25); round(4.85)
3.0
5.0

3. Rounding up

Rounding up requires using 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

4.Respectively Get the integer part and the decimal part

Sometimes we may need to get the integer part and the decimal part respectively. In this case, we can use the modf() method in the math module. This method returns a decimal part and an integer. Partial 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)

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to retain integers in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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