Man16
Man16

Reputation: 147

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

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

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

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

Upvotes: 10

Views: 43545

Answers (6)

Vlad Bezden
Vlad Bezden

Reputation: 89527

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

import math
math.trunc(123.456)

You can also use 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('123')
# 123

Where trunc() function will throw an exception

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()

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

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

Upvotes: 0

Laraconda
Laraconda

Reputation: 707

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

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

Upvotes: 0

Michael0x2a
Michael0x2a

Reputation: 64008

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

>>> 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.trunc will go to 0, whereas math.floor always floors downwards:

>>> 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.floor and math.ceil used to return floats in Python 2.

Also note that int and math.trunc will 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.trunc is specifically for numeric types (and will help make your intent more clear).

Use int if 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 trunc if you want to be absolutely unambiguous about what you mean or if you want to ensure your code works correctly for non-builtin types.

More info below:


Math.floor() in Python 2 vs Python 3

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(...)).

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 vs math.trunc()

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

  • 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 int function is meant to be used when you want to convert a general object into 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__ methods section).
    • The math.trunc function is meant to be used when you want to take an existing real number and specifically truncate and remove its decimals to produce an integral type. This means that unlike int, math.trunc is a purely numeric operation.

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.

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.

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

Upvotes: 26

Shivendra Singh
Shivendra Singh

Reputation: 111

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

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

Upvotes: 2

kyle k
kyle k

Reputation: 5512

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

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

Upvotes: 3

abarnert
abarnert

Reputation: 365697

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.

Upvotes: 1

Related Questions