我如何只在 Python 中舍入一个数字/向下浮动?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19501279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:53:40  来源:igfitidea点击:

How do I ONLY round a number/float down in Python?

pythonintegerrounding

提问by Man16

I will have this random number generated e.g 12.75 or 1.999999999 or 2.65

我将生成这个随机数,例如 12.75 或 1.999999999 或 2.65

I want to always round this number down to the nearest integer whole number so 2.65 would be rounded to 2.

我想始终将此数字向下舍入为最接近的整数整数,因此 2.65 将舍入为 2。

Sorry for asking but I couldn't find the answer after numerous searches, thanks :)

很抱歉问,但经过多次搜索后我找不到答案,谢谢:)

采纳答案by Michael0x2a

You can us either int(), math.trunc(), or math.floor(). They all will do what you want for positive numbers:

您能给我们要么int()math.trunc() ,或math.floor() 。他们都会为正数做你想做的事:

>>> import math
>>> math.floor(12.6)  # returns 12.0 in Python 2
12   
>>> int(12.6)
12
>>> math.trunc(12.6)
12

However, note that they behave differently with negative numbers: int and math.truncwill go to 0, whereas math.flooralways floors downwards:

但是,请注意它们对于负数的行为有所不同:int 并且math.trunc将变为 0,而math.floor始终向下:

>>> import math
>>> math.floor(-12.6)  # returns -13.0 in Python 2
-13
>>> int(-12.6)
-12
>>> math.trunc(-12.6)
-12

Note that math.floorand math.ceilused to return floats in Python 2.

请注意,math.floormath.ceil用于返回 Python 2 中的浮点数。

Also note that intand math.truncwill both (at first glance) appear to do the same thing, though their exact semantics differ. In short: int is for general/type conversion and math.truncis specifically for numeric types (and will help make your intent more clear).

还要注意,intand math.truncwill(乍一看)似乎做同样的事情,尽管它们的确切语义不同。简而言之: int 用于一般/类型转换,math.trunc专门用于数字类型(并且有助于使您的意图更加清晰)。

Use intif you don't really care about the difference, if you want to convert strings, or if you don't want to import a library. Use truncif you want to be absolutely unambiguous about what you mean or if you want to ensure your code works correctly for non-builtin types.

使用int,如果你不真正关心的区别,如果你要转换的字符串,或者如果你不想导入库。使用trunc,如果你想成为绝对不含糊约你的意思,或者如果你想确保你的代码可以正确处理非内建类型。

More info below:

更多信息如下:



Math.floor() in Python 2 vs Python 3

Python 2 与 Python 3 中的 Math.floor()

Note that math.floor(and math.ceil) were changed slightly from Python 2 to Python 3 -- in Python 2, both functions will return a float instead of an int. This was changed in Python 3 so that both methods return an int (more specifically, they call the __float__method on whatever object they were given). So then, if you're using Python 2, or would like your code to maintain compatibility between the two versions, it would generally be safe to do int(math.floor(...)).

请注意,math.floor(和math.ceil)从 Python 2 到 Python 3 略有变化——在 Python 2 中,这两个函数都将返回一个浮点数而不是一个整数。这在 Python 3 中发生了变化,因此两个方法都返回一个 int(更具体地说,__float__它们在给定的任何对象上调用该方法)。因此,如果您使用的是 Python 2,或者希望您的代码保持两个版本之间的兼容性,那么执行int(math.floor(...)).

For more information about why this change was made + about the potential pitfalls of doing int(math.floor(...))in Python 2, see Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

有关为何进行此更改的更多信息 + 关于int(math.floor(...))在 Python 2中执行的潜在陷阱的更多信息,请参阅 为什么 Python 的 math.ceil() 和 math.floor() 操作返回浮点数而不是整数?

int vs math.trunc()

int vs math.trunc()

At first glance, the int()and math.trunc()methods will appear to be identical. The primary differences are:

乍一看,int()math.trunc()方法似乎是相同的。主要区别是:

  • int(...)
    • The int function will accept floats, strings, and ints.
    • Running int(param)will call the param.__int__()method in order to perform the conversion (and then will try calling __trunc__if __int__is undefined)
    • The __int__magic method was not always unambiguously defined -- for some period of time, it turned out that the exact semantics and rules of how __int__should work were largely left up to the implementing class.
    • The intfunction is meant to be used when you want to convert a general objectinto an int. It's a type conversion method. For example, you can convert strings to ints by doing int("42")(or do things like change of base: int("AF", 16) -> 175).
  • math.trunc(...)
    • The trunc will only accept numeric types (ints, floats, etc)
    • Running math.trunc(param)function will call the param.__trunc__()method in order to perform the conversion
    • The exact behavior and semantics of the __trunc__magic method was precisely defined in PEP 3141(and more specifically in the Changes to operations and __magic__ methodssection).
    • The math.truncfunction is meant to be used when you want to take an existing real number and specifically truncate and removeits decimals to produce an integral type. This means that unlike int, math.truncis a purely numeric operation.
  • 内部(...)
    • int 函数将接受浮点数、字符串和整数。
    • 运行int(param)将调用该param.__int__()方法以执行转换(然后将尝试调用__trunc__if __int__is undefined)
    • __int__魔术方法并不总是明确定义-对于一段时间,事实证明,如何准确的语义和规则__int__应该工作在很大程度上留给了实现类。
    • int函数旨在将一般对象转换为 int 时使用。这是一种类型转换方法。例如,您可以通过执行int("42")(或执行诸如更改 base: 之类的操作int("AF", 16) -> 175)将字符串转换为整数。
  • math.trunc(...)
    • trunc 只接受数字类型(整数、浮点数等)
    • 运行math.trunc(param)函数将调用该param.__trunc__()方法以执行转换
    • __trunc__魔术方法的确切行为和语义在PEP 3141(更具体地说,在操作和 __magic__ 方法更改部分)中进行了精确定义。
    • math.trunc当您想要获取现有实数并专门截断和删除其小数以生成整数类型时,可以使用该函数。这意味着不同的是intmath.trunc是一个纯粹的数字运算。

All that said, it turns out all of Python's built-in types will behave exactly the same whether you use int or trunc. This means that if all you're doing is using regular ints, floats, fractions, and decimals, you're free to use either int or trunc.

综上所述,无论您使用 int 还是 trunc,所有 Python 的内置类型的行为都将完全相同。这意味着,如果您所做的只是使用常规整数、浮点数、分数小数,您可以自由使用 int 或 trunc。

However, if you want to be very precise about what exactly your intent is (ie if you want to make it absolutely clear whether you're flooring or truncating), or if you're working with custom numeric types that have different implementations for __int__and __trunc__, then it would probably be best to use math.trunc.

但是,如果您想非常精确地说明您的意图是什么(即,如果您想绝对清楚您是地板还是截断),或者您正在使用具有不同实现的自定义数字类型__int____trunc__,那么最好使用math.trunc.

You can also find more information and debate about this topic on Python's developer mailing list.

您还可以在Python 的开发人员邮件列表上找到有关此主题的更多信息和辩论。

回答by abarnert

I'm not sure whether you want math.floor, math.trunc, or int, but... it's almost certainly one of those functions, and you can probably read the docs and decide more easily than you can explain enough for usb to decide for you.

我不确定您是否想要 math.floor、math.trunc 或 int,但是...几乎可以肯定它是这些函数之一,并且您可能可以阅读文档并做出决定,而不是为 USB 进行足够的解释为你决定。

回答by kyle k

you can do this easily with a built in python functions, just use two forward slashes and divide by 1.

您可以使用内置的 Python 函数轻松完成此操作,只需使用两个正斜杠并除以 1。

>>> print 12.75//1
12.0
>>> print 1.999999999//1
1.0
>>> print 2.65//1
2.0

回答by Shivendra Singh

No need to import any module like math etc.... python bydeafault it convert if you do simply type cast by integer

无需导入任何模块,如数学等.... python bydeafault 它转换,如果你只是按整数类型转换

>>>x=2.65
>>>int(x)
2

回答by Laraconda

Obviously, Michael0x2a's answer is what you should do. But, you can always get a bit creative.

显然,Michael0x2a 的回答是你应该做的。但是,你总是可以变得有点创意。

int(str(12.75).split('.')[0])

回答by Vlad Bezden

If you only looking for the nearest integer part I think the best option would be to use math.trunc()function.

如果您只寻找最接近的整数部分,我认为最好的选择是使用math.trunc()函数。

import math
math.trunc(123.456)

You can also use int()

你也可以使用 int()

int(123.456)

The difference between these two functions is that int() function also deals with string numeric conversion, where trunc() only deals with numeric values.

这两个函数的区别在于int()函数还处理字符串数值转换,而trunc()只处理数值。

int('123')
# 123

Where trunc() function will throw an exception

其中 trunc() 函数会抛出异常

math.trunc('123')

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-62-f9aa08f6d314> in <module>()
----> 1 math.trunc('123')

TypeError: type str doesn't define __trunc__ method

If you know that you only dealing with numeric data, you should consider using trunc() function since it's faster than int()

如果你知道你只处理数字数据,你应该考虑使用 trunc() 函数,因为它比 int() 快

timeit.timeit("math.trunc(123.456)", setup="import math", number=10_000)
# 0.0011689490056596696

timeit.timeit("int(123.456)", number=10_000)
# 0.0014109049952821806