Python: Remove division decimal

前端 未结 7 2040
予麋鹿
予麋鹿 2020-12-29 21:05

I have made a program that divides numbers and then returns the number, But the thing is that when it returns the number it has a decimal like this:

2.0


        
相关标签:
7条回答
  • 2020-12-29 21:11
    if val % 1 == 0:
        val = int(val)
    
    else:
        val = float(val)
    

    This worked for me.

    How it works: if the remainder of the quotient of val and 1 is 0, val has to be an integer and can, therefore, be declared to be int without having to worry about losing decimal numbers.

    Compare these two situations:

    A:

    val = 12.00
    
    if val % 1 == 0:
        val = int(val)
    else:
        val = float(val)
    
    print(val)
    

    In this scenario, the output is 12, because 12.00 divided by 1 has the remainder of 0. With this information we know, that val doesn't have any decimals and we can declare val to be int.

    B:

    val = 13.58
    
    if val % 1 == 0:
        val = int(val)
    else:
        val = float(val)
    
    print(val)
    

    This time the output is 13.58, because when val is divided by 1 there is a remainder (0.58) and therefore val is declared to be a float.

    By just declaring the number to be an int (without testing the remainder) decimal numbers will be cut off.

    This way there are no zeros in the end and no other than the zeros will be ignored.

    0 讨论(0)
  • 2020-12-29 21:19

    There is a math function modf() that will break this up as well.

    import math
    
    print("math.modf(3.14159) : ", math.modf(3.14159))
    

    will output a tuple: math.modf(3.14159) : (0.14159, 3.0)

    This is useful if you want to keep both the whole part and decimal for reference like:

    decimal, whole = math.modf(3.14159)

    0 讨论(0)
  • 2020-12-29 21:21
    >>> int(2.0)
    

    You will get the answer as 2

    0 讨论(0)
  • 2020-12-29 21:22
    def division(a, b):
        return a / b if a % b else a // b
    
    0 讨论(0)
  • 2020-12-29 21:26

    You can call int() on the end result:

    >>> int(2.0)
    2
    
    0 讨论(0)
  • 2020-12-29 21:31

    When a number as a decimal it is usually a float in Python.

    If you want to remove the decimal and keep it an integer (int). You can call the int() method on it like so...

    >>> int(2.0)
    2
    

    However, int rounds down so...

    >>> int(2.9)
    2
    

    If you want to round to the nearest integer you can use round:

    >>> round(2.9)
    3.0
    >>> round(2.4)
    2.0
    

    And then call int() on that:

    >>> int(round(2.9))
    3
    >>> int(round(2.4))
    2
    
    0 讨论(0)
提交回复
热议问题