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

How to keep two decimal places in python

Release: 2019-07-08 09:02:26
Original
81623 people have browsed it

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
>>>
Copy after login

Method 2: Use round built-in function

>>> a = 12.345
>>> round(a, 2)
12.35
Copy after login


Method 3: Use decimal module

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

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'
Copy after login

Method two: Use the re module

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

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!

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