简体   繁体   English

提取浮点数的小数部分

[英]Extract decimal part of a floating point number

I have a function that takes a float as an input and the output is only the decimal part.我有一个 function 将浮点数作为输入,而 output 只是小数部分。 For example, get_decimal(4.45) should return 0.45 , and we should only return positive figures.例如, get_decimal(4.45)应该返回0.45 ,我们应该只返回正数。

I made the following code:我做了以下代码:

def get_decimal(n): 
    try:
        return float('0.'+(str(n).split('.',1))[1])
    except:
        return 0

And this code almost works, but it doesn't give the whole answer.这段代码几乎可以工作,但它并没有给出完整的答案。 For example get_decimal(4.566666678258757587577) only returns:例如get_decimal(4.566666678258757587577)只返回:

0.566666678258757 

instead of:代替:

0.566666678258757587577

Is there a way to get the whole number?有没有办法得到整数?

Use the modulus:使用模数:

inp = 4.566666678258757587577
output = inp % 1
print(output)    # prints 0.566666678259

Note that Python's print() function usually attempts to display a more human readable form of a floating point number.请注意,Python 的print() function 通常会尝试显示更易于阅读的浮点数形式。 So, while the printed value appears to stop after 12 digits, there is more precision beyond that not shown.因此,虽然打印的值似乎在 12 位后停止,但精度超出了未显示的范围。

Consider:考虑:

print((output * 100000) % 1)   # prints 0.667825875724
                               #   4.566666678258757587577  <- original input

you can try this:你可以试试这个:

output = round(inp-int(inp),abs(decimal.Decimal(str(inp)).as_tuple().exponent)

you can use Decimal but in that case you need to set your input as string:您可以使用 Decimal 但在这种情况下,您需要将输入设置为字符串:

from decimal import *

def get_decimal(n): 
    try:
        return Decimal('0.'+(str(n).split('.',1))[1])
    except:
        return 0
print(get_decimal("4.5666666782587575875779"))

output: output:

0.5666666782587575875779

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

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