简体   繁体   English

python:获取没有小数位的数字

[英]python: get number without decimal places

a=123.45324

有没有只返回123的函数?

int will always truncate towards zero: int将始终向零截断:

>>> 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. intmath.floor之间的区别在于math.floor将数字作为浮点数返回,并且不会向零截断。

Python 2.x: Python 2.x:

import math
int( math.floor( a ) )

NB Due to complicated reasons involving the handling of floats, the int cast is safe.注意由于涉及浮点数处理的复杂原因, int是安全的。

Python 3.x: Python 3.x:

import math
math.floor( a )
a = 123.45324
int(a)

You can use the math.trunc() function:您可以使用math.trunc()函数:

a=10.2345
print(math.trunc(a))

If you want both the decimal and non-decimal part:如果你想要小数和非小数部分:

def split_at_decimal(num):
    integer, decimal = (int(i) for i in str(num).split(".")) 
    return integer, decimal

And then:进而:

>>> split_at_decimal(num=5.55)
(5, 55)

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

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