Python output percentages in two ways

Source: Internet
Author: User

Python output percentages in two ways

Note: Test under the PYTHON3 environment.

Mode 1: Direct use of parameter formatting: {:.2%}

{:.2%}: Show 2 digits after decimal point

    • Show 2 digits after the decimal point:
print(‘percent: {:.2%}‘.format(42/50))percent: 84.00%
    • 1
    • 2
    • Do not display decimal digits: {:.0%} , that is, will be 2 changed to 0 :
print(‘percent: {:.0%}‘.format(42/50))percent: 84%
    • 1
    • 2
Mode 2: Format to float and then process into% format: {:.2f}%

The difference from Mode 1 is:

(1) to 42/50 multiply by 100.
(2) on the outside of Mode 2 % { } , Mode 1 is inside % { } .

    • Show 2 digits after the decimal point:
print(‘percent: {:.2f}%‘.format(42/50*100))percent: 84.00%
    • 1
    • 2
    • Show 1 digits after the decimal point:
print(‘percent: {:.1f}%‘.format(42/50*100))percent: 84.0%
    • 1
    • 2
    • Show only integer digits:
print(‘percent: {:.0f}%‘.format(42/50*100))percent: 84%
    • 1
    • 2
Description

{ }Corresponds to format() a parameter, in the default order corresponding to the parameter ordinal starting from 0, {0} corresponding to format() the first parameter, corresponding to the {1} second parameter. For example:

    • Default order:
print(‘percent1: {:.2%}, percent2: {:.1%}‘.format(42/50, 42/100))percent1: 84.00%, percent2: 42.0%
    • 1
    • 2
    • Specify the Order:
      {1:.1%}Corresponds to the 2nd parameter, corresponding to the {0:.1%} 1th parameter.
print(‘percent2: {1:.1%}, percent1: {0:.1%}‘.format(42/50, 42/100))percent2: 42.0%, percent1: 84.0%


Python output percentages in two ways

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.