如何得到小数点后的数字?

我如何得到小数点后的数字?

例如,如果我有 5.55,我如何得到 .55

321235 次浏览

那么:

a = 1.3927278749291
b = a - int(a)


b
>> 0.39272787492910011

或者,使用 numpy:

import numpy
a = 1.3927278749291
b = a - numpy.fix(a)
5.55 % 1

请记住,这不会帮助你解决浮点舍入问题。例如,你可能会得到:

0.550000000001

或者稍微偏离你预期的0.55。

试试模数:

5.55%1 = 0.54999999999999982
import math
orig = 5.55
whole = math.floor(orig)    # whole = 5.0
frac = orig - whole         # frac = 0.55

使用地板并从原始数字中减去结果:

>> import math #gives you floor.
>> t = 5.55 #Give a variable 5.55
>> x = math.floor(t) #floor returns t rounded down to 5..
>> z = t - x #z = 5.55 - 5 = 0.55

使用标准库中的 decimal模块,您可以保持原来的精度,并避免浮点舍入问题:

>>> from decimal import Decimal
>>> Decimal('4.20') % 1
Decimal('0.20')

作为注释中的 仁慈 笔记,您必须首先将本机 float转换为字符串。

>>> n=5.55
>>> if "." in str(n):
...     print "."+str(n).split(".")[-1]
...
.55

一个简单的方法:

number_dec = str(number-int(number))[1:]

另一个疯狂的解决方案是(不使用字符串进行转换) :

number = 123.456
temp = 1


while (number*temp)%10 != 0:
temp = temp *10
print temp
print number


temp = temp /10
number = number*temp
number_final = number%temp
print number_final

使用 妈的:

>>> import math
>>> frac, whole = math.modf(2.5)
>>> frac
0.5
>>> whole
2.0

这是我尝试过的一个解决方案:

num = 45.7234
(whole, frac) = (int(num), int(str(num)[(len(str(int(num)))+1):]))

那么:

a = 1.234
b = a - int(a)
length = len(str(a))


round(b, length-2)

产出:
print(b)
0.23399999999999999
round(b, length-2)
0.234

由于整数被发送到一个小数字符串的长度(’0.234’) ,我们可以只减2而不计算’0’,并计算出所需的小数点数。这种方法在大多数情况下都是有效的,除非你有很多小数位,而且在计算 b 时,舍入误差会干扰舍入的第二个参数。

例如:

import math
x = 5.55
print((math.floor(x*100)%100))

这将在小数点后面给出两个数字,即该示例中的55。如果你需要一个数字你减少了10以上的计算或增加取决于有多少数字你想后的小数。

与公认的答案类似,使用字符串的更简单的方法是

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

浮点数不以十进制(base10)格式存储。通读一下 Python 文档,你就会知道为什么了。因此,从 float 获得 base10表示形式是不可取的。

现在有一些工具允许以十进制格式存储数值数据。下面是一个使用 Decimal库的示例。

from decimal import *


x = Decimal('0.341343214124443151466')
str(x)[-2:] == '66'  # True


y = 0.341343214124443151466
str(y)[-2:] == '66'  # False

有时候后面的零很重要

In [4]: def split_float(x):
...:     '''split float into parts before and after the decimal'''
...:     before, after = str(x).split('.')
...:     return int(before), (int(after)*10 if len(after)==1 else int(after))
...:
...:


In [5]: split_float(105.10)
Out[5]: (105, 10)


In [6]: split_float(105.01)
Out[6]: (105, 1)


In [7]: split_float(105.12)
Out[7]: (105, 12)
import math


x = 1245342664.6
print( (math.floor(x*1000)%1000) //100 )

绝对奏效了

你可能想试试这个:

your_num = 5.55
n = len(str(int(your_num)))
float('0' + str(your_num)[n:])

它将返回 0.55

number=5.55
decimal=(number-int(number))
decimal_1=round(decimal,2)
print(decimal)
print(decimal_1)

输出: 0.55

看看我经常做什么来获得 Python 中小数点后面的数字 3:

a=1.22
dec=str(a).split('.')
dec= int(dec[1])

如果你正在使用熊猫:

df['decimals'] = df['original_number'].mod(1)

另一种选择是与 re.findallre.search一起使用 re模块:

import re




def get_decimcal(n: float) -> float:
return float(re.search(r'\.\d+', str(n)).group(0))




def get_decimcal_2(n: float) -> float:
return float(re.findall(r'\.\d+', str(n))[0])




def get_int(n: float) -> int:
return int(n)




print(get_decimcal(5.55))
print(get_decimcal_2(5.55))
print(get_int(5.55))

输出

0.55
0.55
5

如果您希望简化/修改/探索这个表达式,它已经在 Regex101.com的右上面板中进行了解释。如果您愿意,您还可以在 这个链接中观察它如何与一些样本输入进行匹配。


来源

如何去除附加的浮点数在巨蟒减法?

我发现当使用模1得到分数时,具有非常大的分数部分的非常大的数会导致问题。

import decimal


>>> d = decimal.Context(decimal.MAX_PREC).create_decimal(
... '143000000000000000000000000000000000000000000000000000000000000000000000000000.1231200000000000000002013210000000'
... )
...
>>> d % 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]

相反,我抓住整数部分,并减去它首先帮助简化它的其余部分。

>>> d - d.to_integral()
Decimal('0.1231200000000000000002013210')

另一个使用 modf 的例子

from math import modf
number = 1.0124584


# [0] decimal, [1] integer
result = modf(number)
print(result[0])
# output = 0124584
print(result[1])
# output = 1

一个解决方案是使用模和舍入。

import math


num = math.fabs(float(5.55))
rem = num % 1


rnd_by =   len(str(num)) - len(str(int(num))) - 1


print(str(round(rem,rnd_by)))

您的输出将是0.55

只要使用简单的操作符 分部’/’楼层分部’//’,你就可以很容易地得到任何给定浮点数的分数部分。

number = 5.55


result = (number/1) - (number//1)


print(result)

你可以用这个:

number = 5.55
int(str(number).split('.')[1])

除非你想得到第一个小数

print(int(float(input()) * 10) % 10)

或者你可以试试这个

num = float(input())
b = num - int(num)
c = b * 10
print(int(c))
def fractional_part(numerator, denominator):
if denominator == 0:
return 0
else:
return numerator / denominator - numerator // denominator


print(fractional_part(5, 5)) # Should be 0
print(fractional_part(5, 4)) # Should be 0.25
print(fractional_part(5, 3)) # Should be 0.66...
print(fractional_part(5, 2)) # Should be 0.5
print(fractional_part(5, 0)) # Should be 0
print(fractional_part(0, 5)) # Should be 0

使用数学模块

必须测试它的速度

from math import floor


def get_decimal(number):
'''returns number - floor of number'''
return number-floor(number)

例如:

n = 765.126357123


get_decimal(n)

0.12635712300004798

def fractional_part(numerator, denominator):
# Operate with numerator and denominator to
# keep just the fractional part of the quotient
if  denominator == 0:
return 0
else:
return (numerator/ denominator)-(numerator // denominator)
 



print(fractional_part(5, 5)) # Should be 0
print(fractional_part(5, 4)) # Should be 0.25
print(fractional_part(5, 3)) # Should be 0.66...
print(fractional_part(5, 2)) # Should be 0.5
print(fractional_part(5, 0)) # Should be 0
print(fractional_part(0, 5)) # Should be 0

如果输入是字符串,则可以使用 split ()

decimal = input("Input decimal number: ") #123.456


# split 123.456 by dot = ['123', '456']
after_coma = decimal.split('.')[1]


# because only index 1 is taken then '456'
print(after_coma) # '456'

如果你想做一个数字类型 Print (int (after _ coma)) # 456

为了使它同时适用于正数和负数: 试试 abs(x)%1。对于负数,如果没有 abs,就会出错。

5.55 % 1

产出0.54999999999999998

-5.55 % 1

产出0.4500000000000002

派对后期,留言给新访客。 如果你知道你只需要小数点后2位,然后你可以使用入站轮

round(1.15 % 1, 2)

我尝试了很多其他的解决方案,但没有一个对我有用。

在我的例子中,我有不同的操作,并且总是在最后一步,我的结果比预期的小数要多。

例如:

61 * 0.1 结果是 float < strong > 6.100000000000005

为了得到 6.1,我们必须解析默认的浮点数(至少在我的例子中是64位)到一个更低的浮点数:

import numpy as np


x = 61 * 0.1
y = np.float32(x)

如果之前有很多操作,试着在最后进行铸造:)

要更好地回答最初的问题,答案应该是:

import math
import numpy as np


x_deci, x_inte = math.modf(5.55)
decimals = np.float32(x_deci)

小数的结果是 0.55而不是 0.5499999999999999998

我感兴趣的是这里给出的更合理答案的相对时机。在我的笔记本电脑上使用这个脚本(MacBookPro16,6-Core Intel Core i72.6 GHz) :

#!/bin/sh


python3 -V
python3 -m timeit -s 'a = 5.55' 'b = a % 1'
python3 -m timeit -s 'a = 5.55' 'b = a - a//1'
python3 -m timeit -s 'a = 5.55; import math' 'b = a - math.floor(a)'
python3 -m timeit -s 'a = 5.55' 'b = a - int(a)'
python3 -m timeit -s 'a = 5.55; import math' 'frac, whole = math.modf(a)'

我得到了以下时间:

Python 3.9.10
10000000 loops, best of 5: 34.9 nsec per loop
5000000 loops,  best of 5: 51   nsec per loop
5000000 loops,  best of 5: 69.2 nsec per loop
5000000 loops,  best of 5: 84.1 nsec per loop
5000000 loops,  best of 5: 97.7 nsec per loop

因此,简单的 % 1似乎是最快的方法

a = 12.587
b = float('0.' + str(a).split('.')[-1])