Home  >  Article  >  Backend Development  >  How to keep two decimal places in python

How to keep two decimal places in python

尚
Original
2019-06-26 16:00:5981552browse

How to keep two decimal places in python

The method of retaining two decimal places in Python is as follows:

Retain two decimal places, and Do rounding processing

Method 1: Use string formatting

>>> a = 12.345
>>> print("%.2f" % a)
12.35
>>>

Method 2: Use round built-in function

>>> a = 12.345
>>> round(a, 2)
12.35


Method 3: Use decimal module

>>> from decimal import Decimal
>>> a = 12.345
>>> Decimal(a).quantize(Decimal("0.00"))
Decimal('12.35')

Retain only two decimal places, no rounding required

Method one: Use slices in the sequence

>>> a = 12.345
>>> str(a).split('.')[0] + '.' + str(a).split('.')[1][:2]
'12.34'

Method two: Use the re module

>>> import re
>>> a = 12.345
>>> re.findall(r"\d{1,}?\.\d{2}", str(a))
['12.34']

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

The above is the detailed content of How to keep two decimal places 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