Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: get number without decimal places

Tags:

python

a=123.45324

is there a function that will return just 123?

like image 427
Alex Gordon Avatar asked Aug 03 '10 16:08

Alex Gordon


2 Answers

int will always truncate towards zero:

>>> a = 123.456
>>> int(a)
123
>>> a = 0.9999
>>> int(a)
0
>>> int(-1.5)
-1

The difference between int and math.floor is that math.floor returns the number as a float, and does not truncate towards zero.

like image 100
Mark Rushakoff Avatar answered Sep 23 '22 15:09

Mark Rushakoff


Python 2.x:

import math
int( math.floor( a ) )

N.B. Due to complicated reasons involving the handling of floats, the int cast is safe.

Python 3.x:

import math
math.floor( a )
like image 29
Katriel Avatar answered Sep 21 '22 15:09

Katriel