简体   繁体   English

如何让Python计算百分比结果?

[英]How to make Python calculate result of percentage?

I want Python to be able to the calculate the result of a percentage.我希望 Python 能够计算百分比的结果。

For example: If a drink costs 8, calculate what it costs with 20% added tips (or whatever given percentage).例如:如果一杯饮料的价格为 8,计算它的成本加上 20% 的小费(或任何给定的百分比)。

It then should be 9.6 of course.那么它当然应该是9.6。 I thought I might be able to do it with code something like this:我想我可以用这样的代码来做到这一点:

drink = 8 + 20%

Python doesn't support expressing percentages with the % symbol. Python 不支持用%符号表示百分比。 It can multiply, however.但是,它可以成倍增加。

Increasing a value by 20% means multiplying it by 1.2.将值增加 20% 意味着将其乘以 1.2。

drink = 8 * 1.2

You could write a function if you want to give the percentage and derive the factor:如果要给出百分比并导出因子,可以编写一个函数:

def add_tips(value, percentage):
    return value * (1 + percentage / 100)
>>> drink = 8
>>> add_tips(drink, 20)
9.6

The possibilities are endless.可能性是无止境。

You can always translate percentages to a floating-point value like 20% = 0.2 or 81.7% = 0.817 .您始终可以将百分比转换为浮点值,例如20% = 0.281.7% = 0.817 So simply divide by 100 to transform percentage to floating-point number.因此只需除以100即可将百分比转换为浮点数。 In your case, you want to add 20% of a number to this number aka you want 120% of this number which equates to multiplying with 1.2 .在您的情况下,您想要将一个数字的20%添加到这个数字,也就是您想要这个数字的120% ,这相当于乘以1.2 You can also validate this by calculating 8 + (8 * 0.2) which might be more intuitive.您还可以通过计算8 + (8 * 0.2)来验证这一点,这可能更直观。

给定原始成本和百分比,您可以这样做以获得总金额。

totalCost = cost + (percentage/100)*cost

Python does support the expression of percentages, thanks to the str format() .由于str format() ,Python 确实支持百分比的表达 If you like, you can even mimic that behavior in a unittest.如果你愿意,你甚至可以在单元测试中模仿这种行为。

Example code:示例代码:

def divideby4(x):
    return "{0:.0%}".format(x/4)

Example test:示例测试:

import unittest
import some_silly_calc

class TestCalc(unittest.TestCase):
... 

    def test_divide(self):
        result = some_silly_calc.divideby4(2)
        self.assertEqual(result, "{0:.0%}".format(.50))

Alternative method if you don't want to use "%":如果您不想使用“%”,另一种方法:

def divideby4(x):
    return (x / 4 * 100)

I love how much Python 3+ has evolved since Python 2.7.我喜欢 Python 3+ 自 Python 2.7 以来的发展。 So many cool features!这么多很酷的功能! HTH :) HTH :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM