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

How to express keeping two decimal places in python

步履不停
步履不停 Original
2019-07-03 13:55:18 11060browse

How to express keeping two decimal places in python

There arethree methods,


round(a,2)

'%.2f' % a

Decimal('5.000').quantize(Decimal('0.00'))

When the output result requires two decimal places, the string format: '%.2f' % a is the best method, followed by Decimal.

Note:

1. It can be passed to Decimal integer or string parameters, but it cannot be floating point data, because floating point data itself is not accurate.

2. Decimal can also be used to limit the total number of digits in data.

Talk about the issue of decimal point precision control in Python

Basics

Floating point numbers use the native double precision of the floating point number on the machine (64 bit) expressed. Provides approximately 17 digits of precision and an exponent ranging from -308 to 308. It is the same as the double type in C language. Python does not support 32-bit single-precision floating point numbers. If your program requires precise control over intervals and numerical precision, consider using the numpy extension library.

Python 3.X provides a precision of 17 digits by default for floating point numbers.

Popular explanation about single precision and double precision:

Single precision type and double precision type, their type specifier is float single precision specifier, double double precision specifier. In Turbo C, the single precision type occupies 4 bytes (32 bits) of memory space, its value range is 3.4E-38 ~ 3.4E 38, and can only provide seven significant digits. The double precision type occupies 8 bytes (64 bits) of memory space, its value range is 1.7E-308 ~ 1.7E 308, and can provide 16 significant digits.

Related tutorial recommendations:Python video tutorial

The above is the detailed content of How to express keeping 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