简体   繁体   English

Python 舍入

[英]Python Round_down

I have the following code and result and I would need each number to be rounded to the first decimal but the lowest one ex: 7.166666666666667 to be 7.1 and not 7.2我有以下代码和结果,我需要将每个数字四舍五入到第一位小数但最低的一个例如:7.166666666666667 为 7.1 而不是 7.2

I have tried with round_down but it still rounds up我试过 round_down 但它仍然向上舍入

for x in range(0, 9):
    income_visits=(income_euro[x]/visits[x])
    print(income_visits)

7.166666666666667
7.0
7.666666666666667
11.0
0.1111111111111111
11.333333333333334
162.0
55.0
9.0

here's a little function that does it for you:这是一个小的 function 为你做的:

def round_down(n, decimals=0):
    multiplier = 10 ** decimals
    return math.floor(n * multiplier) / multiplier

make sure to import the math library.确保导入math库。

example usage:用法示例:

print(round_down(1.7777, 1))
print(round_down(1.7777, 2))
print(round_down(1.7777, 3))

output: output:

1.7
1.77
1.777

Here is the solution.这是解决方案。 Try this..试试这个..

number = YOUR_NUMBER number = YOUR_NUMBER

float(str(int(number)) + '.' + str(number-int(number))[2:3])

>>> number = 7.166666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )
7.1
>>> 
>>> number = 7.116666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )
7.1
>>> 
>>> number = 7.196666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )
7.1
>>>
>>> number = 7.096666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )

This could also work.这也可以工作。

num = 7.166666666667
print(int(num*10)/10)

What this does is it takes the number (ie 7.1666...) multiplies it by 10 (71.666...) that way when an integer is taken from it, it returns a whole number (71), then it divides again to get just one decimal place (7.1).它所做的是将数字(ie 7.1666...)乘以 10 (71.666...) ,当从中取出 integer 时,它返回一个整数(71),然后再次除以得到只有一位小数(7.1)。 Hope this helps.希望这可以帮助。

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

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