[Python] Round function

Source: Internet
Author: User

In Python, the round function truncates the decimals by rounding them.

However:

>>> round (3.55, 1) 3.5

The official documentation for the function is interpreted as:

Unfortunately, most decimal fractions cannot is represented exactly as binary fractions. A consequence is so, in general, the decimal floating-point numbers you enter was only approximated by the binary FL Oating-point numbers actually storedin the machine.

>>> Round (0.55, 1) 0.6>>> round (3.55, 1) 3.5
>>> from decimal import decimal>>> decimal (0.55) Decimal (' 0.5500000000000000444089209850062616169452667236328125 ') >>> decimal (3.55) Decimal (' 3.54999999999999982236431605997495353221893310546875 ')

A properly rounded solution is implemented with the decimal module:

 from Import *'17.9555'print Context (prec = Len ( Number.split ('. ' 3 round_half_up). Create_decimal (number)

Explanation of the bold part of the code:

    1. Number is expressed as a string, avoiding the problem of precision caused by floating-point number storage when converting to decimal.
    2. PREC: The preceding Len function is the length of the integer part, followed by 3 is the number of decimal digits reserved.
    3. ROUNDING:ROUND_HALF_UP indicates rounding.

[Python] Round function

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.