如何获取小数点后的数字?
例如,如果有 5.55
,如何获取 .55
?
5.55 % 1
注意,这并不能帮助你解决浮点数舍入问题。例如,你可能会得到:
0.550000000001
或者说,可能会偏离你期望的 0.55。
modf
,它也可能影响精度:math.modf(5.55)
将返回(0.5499999999999998, 5.0)。 - berealx%1
的速度几乎是 x-int(x)
和 modf(x)[0]
方法的两倍(1000000次运行的平均时间分别为980纳秒、1.39微秒和1.47微秒)。我的变量 x
始终为正值,所以我不必担心这个问题。 - coderforlife使用modf函数:
>>> import math
>>> frac, whole = math.modf(2.5)
>>> frac
0.5
>>> whole
2.0
math.modf(2.53) = (0.5299999999999998, 2.0)
,期望的答案是0.53。 - Lord Loh.那么这个怎么样:
a = 1.3927278749291
b = a - int(a)
b
>> 0.39272787492910011
或者,使用numpy:
import numpy
a = 1.3927278749291
b = a - numpy.fix(a)
n = 5.55
,其中 n 是一个浮点数,则应该执行 Decimal(str(n)) % 1
来获取小数部分。(如果您有一个整数,则不需要这样做,但这并不会有任何影响。) - kindall10.0/3 % 1
,至少在我的系统上。 - aherokDecimal.from_float(1.2)
(现在可以写成Decimal(1.2)
),会出现舍入问题,而这个答案是试图避免这种情况的。 - John Ydecimal.Decimal
对象上使用 math.floor
和 math.ceil
时,它们将返回一个 int
类型的值。我认为这是 Python 2 和 3 之间的一个变化。例如,math.floor(decimal.Decimal('4.90'))
返回 4
,math.floor(decimal.Decimal('-4.90'))
返回 -5
,而 type(math.floor(decimal.Decimal('-4.90')))
是 <class 'int'>
。 - undefinednumber_dec = str(number-int(number))[1:]
number_dec = str(number-int(number)).split('.')[1]
- Ryan Allen5.55 % 1
,它也是一个更常用的答案——人们可以在多种编程语言中使用模除法,而上面的答案是针对Python特定的。 - Stewstr(5.55 - int(5.55))[1:]
返回的结果是.5499999999999998
,而不是问题中提到的.55
。 - Cristian Ciupitu尝试使用模运算:
5.55%1 = 0.54999999999999982
abs(x)%1
。 对于负数,如果没有使用abs
,结果会有误差。
5.55 % 1
输出0.5499999999999998
-5.55 % 1
输出0.4500000000000002import math
orig = 5.55
whole = math.floor(orig) # whole = 5.0
frac = orig - whole # frac = 0.55
- macmfrac 0.5499999999999998
def number_after_decimal(number1):
number = str(number1)
if 'e-' in number: # scientific notation
number_dec = format(float(number), '.%df'%(len(number.split(".")[1].split("e-")[0])+int(number.split('e-')[1])))
elif "." in number: # quick check if it is decimal
number_dec = number.split(".")[1]
return number_dec
number = 5.55; "." in number
会出现TypeError: argument of type 'float' is not iterable
错误。如果number = 1e-5
,你会怎么做? - Mark Dickinsonfloat
;Python不会保留任何原始表达格式的知识。我的number = 1e-5
示例同样适用于number = 0.00001
:该数字的str
表示是用科学计数法表示的。顺便说一下,您还需要处理e+
和e-
。 - Mark Dickinson只需使用简单的运算符除法'/' 和 地板除法'//',您就可以轻松获取任何给定浮点数的小数部分。
number = 5.55
result = (number/1) - (number//1)
print(result)
float( '0.' + str(5.55).split('.')[1] )
>>> 0.55。但如果有人有不同的想法,请告诉我。 - Abimael Domínguez