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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3886402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:11:23  来源:igfitidea点击:

How to get numbers after decimal point?

pythonfloating-pointdecimal

提问by l--''''''---------''''''''''''

How do I get the numbers after a decimal point?

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

For example, if I have 5.55, how do i get .55?

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

采纳答案by lllluuukke

An easy approach for you:

一个简单的方法给你:

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

回答by Jim Brissom

What about:

关于什么:

a = 1.3927278749291
b = a - int(a)

b
>> 0.39272787492910011

Or, using numpy:

或者,使用 numpy:

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

回答by jer

5.55 % 1

Keep in mind this won't help you with floating point rounding problems. I.e., you may get:

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

0.550000000001

Or otherwise a little off the 0.55 you are expecting.

或者比您期望的 0.55 稍微低一点。

回答by Juri Robl

Try Modulo:

尝试模数:

5.55%1 = 0.54999999999999982

回答by Kevin Lacquement

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

回答by Kevin Lacquement

Use floor and subtract the result from the original number:

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

回答by intuited

Using the decimalmodule from the standard library, you can retain the original precision and avoid floating point rounding issues:

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

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

As kindallnotesin the comments, you'll have to convert native floats to strings first.

正如评论中的kindall指出的那样,您必须float先将native s转换为字符串。

回答by ghostdog74

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

回答by Romulus

Another crazy solution is (without converting in a string):

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

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

回答by Anthony V

Use modf:

使用modf

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