How Python takes the number of decimal places

Source: Internet
Author: User

Simple Introduction

When writing a data platform, it is necessary to make the statistic of passing rate, so it is unavoidable to have decimal condition. At this point, there will be an infinite number of decimals, then how to make a choice?

Actual operation

You can use the decimal module, which is decimal, which provides decimal floating-point arithmetic support.

Common methods

1. Can be passed to a decimal integer or string parameter, but not floating point data, because the floating-point data itself is inaccurate.

2. To convert from floating-point data to decimal type

From decimal Import *

Decimal.from_float (12.222)

# result is decimal (' 12.2219999999999995310417943983338773250579833984375 ')

3. Define the result style by setting a valid number:

From decimal Import *

GetContext (). prec=6

Decimal (1)/decimal (7)

# The result is a decimal (' 0.142857 '), six valid digits

4. Rounding, keeping several decimals

From decimal Import *

Decimal (' 50.5679 '). Quantize (Decimal (' 0.00 '))

# result is decimal (' 50.57 '), result rounding retains two decimal places

5.Decimal result converted to string

From decimal Import *

STR (Decimal (' 3.40 '). Quantize (Decimal (' 0.0 ')))

# result is ' 3.40 ', String type

Effect

Reference:

Decimal module

How Python takes the number of decimal places

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.