【问题标题】:How to return the fractional part of a number? [closed]如何返回数字的小数部分? [关闭]
【发布时间】:2021-03-08 19:55:04
【问题描述】:

如何获得数字的小数部分?

例如,我有一个浮点数列表num = [12.73, 9.45],并且只想获取小数点后的数字,在这种情况下为7345。我该怎么做?

【问题讨论】:

  • 到目前为止你尝试过什么?也许将值设为字符串并调用 .split('.')?
  • 请从intro tour 重复on topichow to ask。 “告诉我如何解决这个编码问题?”与 Stack Overflow 无关。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。 Stack Overflow 无意取代现有的教程和文档。
  • 本网站无法替代阅读(大量!)可用的 Python 语言教程之一,
  • 这能回答你的问题吗? How to get numbers after decimal point?

标签: python python-3.x


【解决方案1】:
num = [12.73, 9.45];
result = list(map(lambda x: int(str(x).split('.')[1]),num))
print(result)

【讨论】:

    【解决方案2】:

    一种方法是使用纯(ish)数学。

    简短的回答:

    num = [12.73, 9.45]
    
    [int((f % 1)*100) for f in num]
    
    >>> [73, 44]
    

    说明:

    整个除法完成后,modulo operator 返回余数(过于简化)。

    因此,返回十进制值;数字的小数部分。

    12.73 % 1
    
    >>> 0.7300000000000004
    

    要将十进制值作为整数获取,可以使用:

    int((12.73 % 1)*100)
    
    >>> 73
    

    只需将其包装在一个循环中以获取所有必需的值...您就会得到上面的“简短答案”。

    【讨论】:

    • 感谢您的帮助。
    • 我的荣幸 - 希望这是有道理的。干杯!
    【解决方案3】:

    并且只想得到句号之后的数字,

    没有这样的事情。数字没有位;数字的字符串表示有数字。即便如此,浮点数也不精确;您可能会在一种情况下显示0.3,而在另一种情况下显示0.30000000000000004对于相同的值

    听起来您实际上想要的是fractional part of 数字。有很多方法可以做到这一点,但它们都归结为同一个想法:这是将输入(作为浮点数)除以 1 的结果。

    对于单个值,它看起来像:

    fractional_part = value % 1.0
    

    # This built-in function performs the division and gives you
    # both quotient and remainder.
    integer_part, fractional_part = divmod(value, 1.0)
    

    import math
    fractional_part = math.fmod(value, 1.0)
    

    import math
    # This function is provided as a special case.
    # It also gives you the integer part.
    # Notice that the results are the other way around vs. divmod!
    fractional_part, integer_part = math.modf(value)
    

    要以相同方式处理列表中的每个值,请使用list comprehension

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 2013-05-13
      • 2018-06-04
      相关资源
      最近更新 更多