English 中文(简体)
如何获取小数点后的数字?
原标题:How to get numbers after decimal point?

如何获取小数点后的数字?

例如,如果我有<code>5.55</code>,我如何获得<code>.55</code>?

最佳回答

一种简单的方法:

number_dec = str(number-int(number))[1:]
问题回答
5.55 % 1

请记住,这对您解决浮点舍入问题没有帮助。也就是说,你可能会得到:

0.550000000001

或者在其他方面稍微低于你预期的0.55。

使用模式

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

关于:

a = 1.3927278749291
b = a - int(a)

b
>> 0.39272787492910011

或者,使用numpy:

import numpy
a = 1.3927278749291
b = a - numpy.fix(a)

使用decimal模块,您可以保留原始精度并避免浮点舍入问题:

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

作为kindall注意在注释中,您必须首先将本机float转换为字符串。

试试Modulo:

5.55%1 = 0.54999999999999982

To make it work with both positive and negative numbers: try abs(x)%1. For negative numbers, without with abs, it will go wrong.

5.55%1

输出0.5499999999999998

-5.55%1

产量4亿50000000000002

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

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

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
>>> n=5.55
>>> if "." in str(n):
...     print "."+str(n).split(".")[-1]
...
.55

只需使用简单的运算符除法//地板除法//,您就可以轻松地获得任何给定浮点的分数部分。

number = 5.55

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

print(result)

有时尾随零很重要

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)

使用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

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

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

浮点数不以十进制(以10为基础)格式存储。阅读python文档来满足自己的原因。因此,从float中获取base10表示是不可取的。

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

from decimal import *

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

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

如果输入是字符串,我们可以使用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 

if you want to make a number type print(int(after_coma)) # 456

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

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

示例:

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

这将在小数点后给出两个数字,即该示例中的55。如果你需要一个数字,你可以将上面的计算减少10,或者根据小数后你想要的数字增加。

import math

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

它确实奏效了

另一种选择是将re模块与re一起使用。findallre。search

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

Output

0.55
0.55
5

如果您希望简化/修改/探究表达式,请参阅regex101.com。如果您愿意,也可以在这个链接,它将如何与一些样本输入匹配。


Source

如何在python减法中去掉额外的浮点数

您可以使用此:

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

Using math module

必须测试其速度

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
a = 12.587
b = float( 0.  + str(a).split( . )[-1])

关于:

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

round(b, length-2)

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

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

你可能想试试这个:

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

See what I often do to obtain numbers after the decimal point in python 3:

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

如果您正在使用熊猫:

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




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...